Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create a new array and push into it in one line - Javascript OOP

I've this code with a function, wherein a I'm trying to define an array then on the next line pushing to it:

function Spot(value) {
  this.x = null;
  this.y = null;
  this.values = [];
  this.values.push(value);
}

I've tried this:

this.values = [].push(value);

and

this.values = (this.values || []).push(value);

But failed. Is there something wrong with the code.....

like image 329
popeye Avatar asked Dec 08 '25 06:12

popeye


2 Answers

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.

like image 157
freedomn-m Avatar answered Dec 09 '25 19:12

freedomn-m


Just take the value in an array.

function Spot(value) {
    this.x = null;
    this.y = null;
    this.values = [value];
}

var point = new Spot('foo')

console.log(point);
like image 37
Nina Scholz Avatar answered Dec 09 '25 21:12

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!