Populating another array from array - Javascript

后端 未结 8 1588
我寻月下人不归
我寻月下人不归 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:47

    You have misspelled variable ar Try this

    for(i=0;i<ar.length;i++){
        bar[i]=ar[i];
    }
    alert(ar[1]);
    
    0 讨论(0)
  • 2020-12-29 22:47

    The problem probably here in the for loop statement:

    for(i=0;i<ar.length;i++){
        bar[i]=ar[i];
    }
    alert(ar[1]);
    

    You need to fix to ar.length instead of arr.length. And it's better to initialize bar as: var bar = [].

    0 讨论(0)
  • 2020-12-29 22:49

    In ES6 you can use Array.from:

    var ar = ["apple","banana","canaple"];
    var bar = Array.from(ar);
    alert(bar[1]); // alerts 'banana'
    
    0 讨论(0)
  • 2020-12-29 22:50

    In your code, the variable arr in the for loop is not the same as your original array ar: you have one too many r.

    0 讨论(0)
  • 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();
    
    0 讨论(0)
  • 2020-12-29 22:54

    With ES6+ you can simply do this

    const original = [1, 2, 3];
    const newArray = [...original];
    

    The documentation for spread syntax is here

    To check, run this small code on dev console

    const k = [1, 2];
    const l = k
    k === l
    > true
    const m = [...k]
    m
    > [1, 2]
    k === m
    > false
    
    0 讨论(0)
提交回复
热议问题