简体   繁体   English

Javascript / React Native中的奇怪数组行为

[英]Weird array behavior in Javascript / React Native

I'm new in ReactNative / Javascript. 我是ReactNative / Java语言的新手。 One weird thing that I notice is that if I have an array from parameter (ex: [1, 0, 1, -1] ) and assign it to another variable and console.log it, I will get like an infinite array content. 我注意到的一件奇怪的事情是,如果我有一个来自参数的数组(例如[1, 0, 1, -1] )并将其分配给另一个变量并进行console.log ,我将得到一个无限数组内容。

myFunc = (array) => {
  console.log("ARRAY:");
  console.log(array);
  var result = array;
  console.log("RESULT:");
  console.log(result);
}

Resulting console log in iOS: 在iOS中生成的控制台日志:

ARRAY:
[ 1, 0, 1, -1 ]
RESULT:
[ 1,
  0,
  1,
  -1,
  ,
  ,
  ,
  ,
  ,
  ,
  ,
  ,
  ,
  ,
  ,
  ,
  ,
  ,
  ,
  ,
  ,
  ,
  ,
  ,
  ,
  ,
  ,
  ,
  ,
  ,
  ,
  ,
  ,
  ,
  ,
  ,
  ,
  ,
  ,
  ,
  ... 100 more rows
  ,
  [] ]

Why is this happening? 为什么会这样呢? And how to correctly assigning array contents from one variable to another? 以及如何正确地将数组内容从一个变量分配给另一个?

Note that this only happens if the data is gotten from parameter. 请注意,只有从参数获取数据时,才会发生这种情况。 If I casually have var array = [1, 0, 1, -1] and assign it to another variable, there's no problem with that. 如果我随便使用var array = [1, 0, 1, -1]并将其分配给另一个变量,那没有问题。

I tried to reproduce this but the result is as expected. 我试图重现结果,但结果与预期的一样。

Without more information to do debugging and investigating. 没有更多的信息来进行调试和调查。 I think the biggest culprit might be the way OP copy the array. 我认为最大的罪魁祸首可能是OP复制阵列的方式。

By doing 通过做

var result = array;

If array value somehow changed, all changes will be reflected in result as well. 如果array值以某种方式更改,则所有更改也将反映在result中。 ( example here ) 这里的例子

You can try to use slice() . 您可以尝试使用slice()

var result = array.slice();

This answer over here explain a lot about why slice() prevents problem above. 这里的答案解释了很多关于slice()防止上述问题的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM