简体   繁体   中英

Weird array behavior in Javascript / React Native

I'm new in ReactNative / Javascript. 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.

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

Resulting console log in 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.

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.

By doing

var result = array;

If array value somehow changed, all changes will be reflected in result as well. ( example here )

You can try to use slice() .

var result = array.slice();

This answer over here explain a lot about why slice() prevents problem above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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