Quantcast
Channel: create a new array and push into it in one line - Javascript OOP - Stack Overflow
Viewing all articles
Browse latest Browse all 4

Answer by fdomn-m for create a new array and push into it in one line - Javascript OOP

$
0
0

You are missing the array-initialisation syntax:

var x = [ 1, 2, 3 ];

in your case, this would be:

this.values = [ value ];

More info here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array


The code:

var x = ([]).push("y");

looks like it should generate an array and push the value to it. It does create the array, however the array is not returned to x, the new length of the array is returned, ie 1.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

The push() method adds one or more elements to the end of an array and returns the new length of the array. [emphasis mine]


As noted in the comments, an alternative that is closer to your original attempt would be:

var x = ([]).concat("y");

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.


Viewing all articles
Browse latest Browse all 4

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>