为什么将元素推送到 concat( ) 返回的新数组中会返回数组的大小而不是数组本身

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      更新时间:2023-09-26
<!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"]

根据定义,push() 方法返回调用该方法的对象的 new 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.