Javascript - 为什么从函数返回array.push(x)不会将元素x推入数组? [英] Javascript - Why returning array.push(x) from a function doens't push the element x into the array?

查看:107
本文介绍了Javascript - 为什么从函数返回array.push(x)不会将元素x推入数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  function foo(list){
var array = [];
array.push(list);
返回数组;
}

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



< p $>

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

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

它们有什么区别?

解决方案

如果你看一下 push 方法,它返回推后的数组长度,而不是数组本身,这就是为什么返回1 。
$ b


push()方法将一个或多个元素添加到数组的末尾,
返回数组。

您将一个包含3个元素的数组推向新数组,因此在新数组中,您有一个数组作为其内容因此1被返回

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?

解决方案

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

这篇关于Javascript - 为什么从函数返回array.push(x)不会将元素x推入数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆