Javascript - Why returning array.push(x) from a function doens#39;t push the element x into the array?(Javascript - 为什么从函数返回 array.push(x) 不会将元素 x 推送到数组中?)
问题描述
我想知道为什么以下函数有效:
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]]
虽然这个没有:
function foo(list){
var array = [];
return array.push(list);
}
> foo([1,2,3])
1
它们有什么区别?
推荐答案
如果你看一下push 方法,它返回push后数组的长度,而不是数组本身,所以它返回1.
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.
push() 方法将一个或多个元素添加到数组的末尾,并且返回数组的新长度.
The push() method adds one or more elements to the end of an array and returns the new length of the array.
您正在将一个包含 3 个元素的数组推送到新数组,因此在新数组中您有一个数组作为其内容,因此返回 1
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 推送到数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Javascript - 为什么从函数返回 array.push(x) 不会将元素 x 推送到数组中?


基础教程推荐
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 直接将值设置为滑块 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01