1

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.

Chen Li Yong
  • 5,459
  • 8
  • 58
  • 124

1 Answers1

-4

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.

Zendy
  • 774
  • 7
  • 23
  • I was trying to answer the question "And how to correctly assigning array contents from one variable to another?". – Zendy Apr 16 '19 at 08:12
  • Oh hey, wait, this actually gave me correct [1, 0, 1, -1] data! Why is that?? – Chen Li Yong Apr 16 '19 at 08:14
  • @Zendy If this is the correct answer, please explain why, because just right now, this looks like black magic! – sjahan Apr 16 '19 at 08:22
  • I tried with some other array assignments, even array within array assignments, and it still works. But reading the slice() information, it returns "shallow copy" of the original. I don't know whether it works by removing those extra nil elements if I don't supply any parameters. – Chen Li Yong Apr 16 '19 at 08:29
  • @ChenLiYong I updated the answer with some investigation result. See if that was your problem. – Zendy Apr 16 '19 at 08:32
  • @sjahan thank you for your feedback. I updated the answer. If there is more room for improvement, Please let me know. – Zendy Apr 16 '19 at 08:33