1

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?

0

5 Answers 5

3

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'; })());
Sign up to request clarification or add additional context in comments.

Comments

3

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

1 Comment

That may not seem much shorter, but if you're doing it with aReallyReallyLongVariableName, not having to (mis)type it twice is convenient.
2

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

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.