简体   繁体   English

即时将简单值推入数组

[英]Pushing simple value into an array on the fly

I want to be able to create an array with only one value inside of it on the fly without using a variable.我希望能够在不使用变量的情况下动态创建一个只有一个值的数组。 This works with a variable:这适用于一个变量:

var arr = [];
arr.push('test');
console.log(arr); // correctly logs ["test"]

But this does not:但这不会:

console.log([].push('test')); // logs 1

Why does this log 1 instead of ["test"] ?为什么这个日志1而不是["test"] Is this coerced into a boolean?这是强制转换为 boolean 吗?

Array.prototype.push returns the new length of the array, not the pushed item nor the array it-self. Array.prototype.push返回数组的新length ,而不是推送的项目或数组本身。

"I want to be able to create an array with only one value inside of it on the fly without using a variable" “我希望能够在不使用变量的情况下动态创建一个只有一个值的数组”

const arr = ['test'];

 console.log(['test']);

Array.prototype.push()

The push() method adds one or more elements to the end of an array and returns the new length of the array . push()方法将一个或多个元素添加到数组的末尾并返回数组的新长度

In the first example you are first pushing the element in the array then log the array.在第一个示例中,您首先将元素推送到数组中,然后记录数组。 But in the second example you are logging the returned result of push() .但在第二个示例中,您正在记录push()的返回结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM