Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
49
rated 0 times [  53] [ 4]  / answers: 1 / hits: 137815  / 13 Years ago, wed, april 27, 2011, 12:00:00

Code



var cool = new Array(3);
cool[setAll] = 42; //cool[setAll] is just a pseudo selector..
alert(cool);


Result



A alert message:



42,42,42


How do I change/set all values of an array to a specific value?


More From » arrays

 Answers
15

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)


[#92535] Tuesday, April 26, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
wyattkennyc

Total Points: 650
Total Questions: 102
Total Answers: 90

Location: Monaco
Member since Mon, May 23, 2022
2 Years ago
;