Javascript | Set all values of an array
There's no built-in way, you'll have to loop over all of them:
function setAll(a, v) {
var i, n = a.length;
for (i = 0; i < n; ++i) {
a[i] = v;
}
}
http://jsfiddle.net/alnitak/xG88A/
If you really want, do this:
Array.prototype.setAll = function(v) {
var i, n = this.length;
for (i = 0; i < n; ++i) {
this[i] = v;
}
};
and then you could actually do cool.setAll(42)
(see http://jsfiddle.net/alnitak/ee3hb/).
Some people frown upon extending the prototype of built-in types, though.
EDIT ES5 introduced a way to safely extend both Object.prototype
and Array.prototype
without breaking for ... in ...
enumeration:
Object.defineProperty(Array.prototype, 'setAll', {
value: function(v) {
...
}
});
EDIT 2 In ES6 draft there's also now Array.prototype.fill
, usage cool.fill(42)
The ES6 approach is very clean. So first you initialize an array of x length, and then call the fill
method on it.
let arr = new Array(3).fill(9)
this will create an array with 3 elements like:
[9, 9, 9]