Alex
Alex

Reputation: 5724

JS array append

I am trying to do...

a=['a',2,3];
a+=function(){return 'abc'};
console.log(a[3]);

Ergo I want to a.push() in a shorthand way.

Is there any kind of operator that will allow me to do this?

Upvotes: 1

Views: 1073

Answers (5)

Paul
Paul

Reputation: 141839

a.push(value) is the shorthand way haha. The other way is a[a.length] = value

Upvotes: 3

Mike Samuel
Mike Samuel

Reputation: 120496

No, ES5 getter-setters allow you to intercept assignments = but there is no operator overloading to allow intercepting and reinterpreting + or +=.

If you knew the content being added was a single primitive value, you could fake it.

var appendable = {
   x_: [1, 2],
   get x() { return this.x_; },
   set x(newx) { this.x_.push(newx.substring(("" + this.x_).length)); }
};

alert(appendable.x);
appendable.x += 3;
alert(appendable.x);  // alerts 1,2,3 not 1,23
alert(appendable.x.length);

but really, .push is the best way to push content onto the end of an array.

Upvotes: 0

Matthew
Matthew

Reputation: 15952

No - and in any case, there's nothing wrong with:

var a = ['a', 'b', 'c'];
a.push('d');

If you want to push a return value:

a.push((function() { return 'e'; })());

Upvotes: 3

hugomg
hugomg

Reputation: 69934

You can convert your string to an array using .split():

'123'.split('');

And then use .concat() to append the results:

a = a.concat( '123'.split() )

Of course, you can always wrap this up inside a function if you so desire.

Upvotes: 0

meder omuraliev
meder omuraliev

Reputation: 186552

You can't do operator overloading as far as I know, so that isn't possible.

Upvotes: 2

Related Questions