+ 1
Array push JavaScript vs Ruby
My first programming language is Ruby. Today I ran into a strange issue in my code in JavaScript. //Node.js var array = [ ]; array = array.push(0); console.log(array); //Strangely the output is 1. Why?? #Ruby array = [ ] array = array.push(0) print(array) As expected the output is [0]. Could anyone please explain the difference in output in these (very similar) codes in Ruby and JavaScript?
3 odpowiedzi
+ 1
Yes, push on a JavaScript array returns the length of the array as was said above. That's the new length (after the push). This is different from Ruby where the array you're pushing to is returned.
It's important to remember not to save the value of a push like this in JavaScript.
+ 4
This will return the expected output.
var array = [];
array.push(0);
console.log(array);
The push() returns the length of the array which is the reason behind it printing 1.
+ 3
Like append in python, the push() function in ruby used to push one or more elements into the array just like adding a new element in an array.