【问题标题】:Why does pushing an element into a new Array returned by a concat( ) return the size of the array instead of the array itself?为什么将一个元素推入由 concat() 返回的新数组中返回的是数组的大小而不是数组本身?
【发布时间】:2015-01-11 04:09:30
【问题描述】:
<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var a = ['a','b'];
var b = ['c','d'];
var c = a.concat(b).push('e');
document.getElementById("demo").innerHTML = c;
</script>

</body>
</html>

这将导致数字 '5',而不是 ['a','b','c','d','e']

【问题讨论】:

标签: javascript arrays concat chain


【解决方案1】:

根据定义,push() 方法返回调用该方法的对象的新 length 属性。

方法所在对象的新长度属性 调用。

这里,

a.concat(b) //returns an `array`. But wait, the statement still has a method chained,
            //and to be evaluated.
(returned array).push('e'); // the chained push() is invoked on the returned array.

依次返回新形成的数组的length。 所以语句最终的返回值就是数组的length,存储在c变量中。

要通过concat() 操作捕获返回的array,您可以修改代码以将链接的方法分解为多个语句,如下所示:

var c = a.concat(b);
c.push('e');
console.log(c) // prints the array content.

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-05
  • 1970-01-01
  • 2016-08-20
  • 2021-10-04
  • 2022-01-18
  • 2022-01-12
  • 1970-01-01
相关资源
最近更新 更多