代码
var cool = new Array(3);
cool[setAll] = 42; //cool[setAll] is just a pseudo selector..
alert(cool);
结果
警告信息:
42,42,42
如何将数组的所有值更改/设置为特定值?
最佳答案
没有内置方法,您必须遍历所有方法:
function setAll(a, v) {
var i, n = a.length;
for (i = 0; i < n; ++i) {
a[i] = v;
}
}
http://jsfiddle.net/alnitak/xG88A/
如果您真的想要,请执行此操作:
Array.prototype.setAll = function(v) {
var i, n = this.length;
for (i = 0; i < n; ++i) {
this[i] = v;
}
};
然后您实际上可以执行 cool.setAll(42)
(参见 http://jsfiddle.net/alnitak/ee3hb/)。
不过,有些人不赞成扩展内置类型的原型(prototype)。
编辑 ES5 引入了一种方法来安全地扩展 Object.prototype
和 Array.prototype
而不会破坏 for ... ...
枚举:
Object.defineProperty(Array.prototype, 'setAll', {
value: function(v) {
...
}
});
EDIT 2 在 ES6 草案中现在还有 Array.prototype.fill
,用法 cool.fill(42)
关于Javascript |设置数组的所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5802762/