JS数组追加

时间:2011-07-21 18:53:51

标签: javascript

我想做...

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

我想以简写的方式来a.push()。

是否有任何类型的操作员可以让我这样做?

5 个答案:

答案 0 :(得分:3)

a.push(value)是简写方式哈哈。另一种方式是a[a.length] = value

答案 1 :(得分:3)

不 - 在任何情况下,都没有错:

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

如果要推送返回值:

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

答案 2 :(得分:2)

据我所知,你不能做运算符重载,所以这是不可能的。

答案 3 :(得分:0)

您可以使用.split()将字符串转换为数组:

'123'.split('');

然后使用.concat()附加结果:

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

当然,如果你愿意的话,你总是可以将它包装在一个函数中。

答案 4 :(得分:0)

不,ES5 getter-setters允许您截取作业=,但没有运算符重载以允许拦截和重新解释++=

如果您知道要添加的内容是单个原始值,则可以伪造它。

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);

但实际上,.push是将内容推送到数组末尾的最佳方式。