为什么将一个元素推入由 concat( ) return 编辑的新数组 return 是数组的大小而不是数组本身?
Why does pushing an element into a new Array returned by a concat( ) return the size of the array instead of the array itself?
<!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() 方法 return 是调用该方法的对象的新 length
属性。
The new length property of the object upon which the method was
called.
这里,
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.
又 return 是新形成的数组的 length
。
所以语句最后的return值为数组的length
,保存在c
变量中
要通过 concat()
操作捕获 returned array
,您可以修改代码以将链接的方法分解为多个语句,如下所示:
var c = a.concat(b);
c.push('e');
console.log(c) // prints the array content.
<!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() 方法 return 是调用该方法的对象的新 length
属性。
The new length property of the object upon which the method was called.
这里,
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.
又 return 是新形成的数组的 length
。
所以语句最后的return值为数组的length
,保存在c
变量中
要通过 concat()
操作捕获 returned array
,您可以修改代码以将链接的方法分解为多个语句,如下所示:
var c = a.concat(b);
c.push('e');
console.log(c) // prints the array content.