开发者

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?


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'; })());


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


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜