Javascript - Why returning array.push(x) from a function doens't push the element x into the array?

后端 未结 1 1704
没有蜡笔的小新
没有蜡笔的小新 2021-01-14 08:31

I\'d like to know why the following function works:

function foo(list){
    var array = [];
    array.push(list);
    return array;
}

> foo([1,2,3])
[[1,         


        
1条回答
  •  萌比男神i
    2021-01-14 08:58

    If you look at the definition of the push method, it returns the length of the array after the push, not the array itself, that is why it is returning 1.

    The push() method adds one or more elements to the end of an array and returns the new length of the array.

    You are pushing an array with 3 elements to the new array, so in the new array you have an array as its content thus 1 is returned

    0 讨论(0)
提交回复
热议问题