admin 管理员组

文章数量: 1086019

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,2,3]]

while this one doesn't:

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

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

What's the difference between them?

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,2,3]]

while this one doesn't:

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

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

What's the difference between them?

Share Improve this question edited Feb 22, 2018 at 12:52 Marco Bonelli 69.7k21 gold badges127 silver badges146 bronze badges asked Apr 7, 2015 at 1:30 Bruno HenriqueBruno Henrique 79710 silver badges21 bronze badges 2
  • 4 Because push doesn't return the array you're pushing on to. – Dave Newton Commented Apr 7, 2015 at 1:34
  • Read the docs: developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – epascarello Commented Apr 7, 2015 at 2:03
Add a ment  | 

1 Answer 1

Reset to default 10

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

本文标签:

Error[2]: Invalid argument supplied for foreach(), File: /www/wwwroot/roclinux.cn/tmp/view_template_quzhiwa_htm_read.htm, Line: 58
File: /www/wwwroot/roclinux.cn/tmp/route_read.php, Line: 205, include(/www/wwwroot/roclinux.cn/tmp/view_template_quzhiwa_htm_read.htm)
File: /www/wwwroot/roclinux.cn/tmp/index.inc.php, Line: 129, include(/www/wwwroot/roclinux.cn/tmp/route_read.php)
File: /www/wwwroot/roclinux.cn/index.php, Line: 29, include(/www/wwwroot/roclinux.cn/tmp/index.inc.php)