Javascript Syntax: Var Array = [].push(foo);
Solution 1:
When you use push method it returns length of array. So when you do:
var array = [10,20].push(foo);
you get [10, 20, foo] length of this array is three. But as you say var array it stores returned length from push method in this variable.
Solution 2:
instead you can try
var array, foo = 30;
(array = [10,20]).push(foo);
console.log(array)
Solution 3:
push
is a function and it returns an integer representing the length of the array.
Imagine the definition of this function as
int push(object obj);
When you do this:
var array = [].push(foo);
You are actually running the function and returning the value.
Solution 4:
Because the return value of push is the new length of the array Documentation and examples.
In your second example, you cited outputting the array, which is going to give you the new array in both cases. However, the returned result of your second case is the new array length as well
var array = [];
array.push(foo); //If you do this in the console, you'll see that 1 gets returned.
console.log(array); //While this will print out the actual contents of array, ie. foo
Solution 5:
Array.prototype.push()
always returns the new number of elements in the array. It does not return this
instance or a new Array instance. push()
is a mutator actually changes the contents of the array.
Post a Comment for "Javascript Syntax: Var Array = [].push(foo);"