简体   繁体   中英

Why the push method doesn't work in this case : [].push

I want to use the function push() directly in the array declaration, but its not working properly. In my example, my array return the value 2 :

 var j = ["b"].push("a"); document.write(j); // return 2 

Why my array returns the value 2 instead of ["b", "a"] ?

.push returns:

The new length property of the object upon which the method was called

So ["b"] you have an array. ["b"].push("a") , yes it is now ["b", "a"] but since you didn't assign it, you are left with the result of the push call which is its new length, 2. You can either assign it separately:

var j = ["b"];
j.push("a");
console.log(j);

Or use .concat

returns a new array comprised of the array on which it is called joined with the array(s) and/or value(s) provided as arguments.

var j = ["b"].concat("a");
console.log(j);

The push() method adds new items to the end of an array, and returns the new length.

 var j = ["b"].push("a"); console.table(j); // return 2 // this is correct 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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