JavaScript的|将数组的所有值 [英] Javascript | Set all values of an array

查看:58
本文介绍了JavaScript的|将数组的所有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

code

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

结果

一个警报消息:

42,42,42

如何更改/设置数组的所有值到一个特定的值?

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

推荐答案

有没有内置的方式,你必须遍历所有的人:

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

然后你可以真正做到 cool.setAll(42)(见 HTTP ://jsfiddle.net/alnitak/ee3hb/

有些人看不惯延长的原型内置类型,虽然。

Some people frown upon extending the prototype of built-in types, though.

修改 ES5提供了一种方法来安全地扩展双方的Object.prototype Array.prototype 不破的for ... in ... 枚举:

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) {
        ...
    }
});

编辑2 在ES6草案现在也 Array.prototype.fill ,使用 cool.fill(42)

EDIT 2 In ES6 draft there's also now Array.prototype.fill, usage cool.fill(42)

这篇关于JavaScript的|将数组的所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆