Populating another array from array - Javascript

后端 未结 8 1663
我寻月下人不归
我寻月下人不归 2020-12-29 22:12

Very simple thing I am trying to do in JS (assign the values of one array to another), but somehow the array bar\'s value doesn\'t seem affected at all.

<
8条回答
  •  醉酒成梦
    2020-12-29 22:54

    Your code isn't working because you are not initializing bar:

    var bar = [];
    

    You also forgot to declare your i variable, which can be problematic, for example if the code is inside a function, i will end up being a global variable (always use var :).

    But, you can avoid the loop, simply by using the slice method to create a copy of your first array:

    var arr = ["apple","banana","canaple"];
    var bar = arr.slice();
    

提交回复
热议问题