Javascript | 设置数组的所有值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5802762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:57:35  来源:igfitidea点击:

Javascript | Set all values of an array

javascriptarrays

提问by Tomkay

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?

如何将数组的所有值更改/设置为特定值?

回答by Alnitak

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/

http://jsfiddle.net/alnitak/xG88A/

If you reallywant, 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/).

然后你实际上可以做cool.setAll(42)(见http://jsfiddle.net/alnitak/ee3hb/)。

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

不过,有些人不赞成扩展内置类型的原型。

EDITES5 introduced a way to safely extend both Object.prototypeand Array.prototypewithout breaking for ... in ...enumeration:

编辑ES5引入的方式安全地扩展双方Object.prototypeArray.prototype没有打破for ... in ...列举:

Object.defineProperty(Array.prototype, 'setAll', {
    value: function(v) {
        ...
    }
});

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

编辑 2在 ES6 草案中,现在还有Array.prototype.fill用法cool.fill(42)

回答by Faris Zacina

The ES6 approach is very clean. So first you initialize an array of x length, and then call the fillmethod on it.

ES6 方法非常干净。所以首先你初始化一个 x 长度的数组,然后调用fill它的方法。

let arr = new Array(3).fill(9)

this will create an array with 3 elements like:

这将创建一个包含 3 个元素的数组,例如:

[9, 9, 9]

回答by mustafa.0x

mapis the most logical solution for this problem.

map是这个问题最合乎逻辑的解决方案。

let xs = [1, 2, 3];
xs = xs.map(x => 42);
xs // -> [42, 42, 42]

However, if there is a chance that the array is sparse, you'll need to use foror, even better, for .. of.

但是,如果数组有可能是稀疏的,您将需要使用,for或者更好的是,for .. of.

See:

看:

回答by Quentin

Use a forloop and set each one in turn.

使用for循环并依次设置每个循环。

回答by Сергей Язев

Actually, you can use this perfect approach:

实际上,您可以使用这种完美的方法:

let arr = Array.apply(null, Array(5)).map(() => 0);
// [0, 0, 0, 0, 0]

This code will create array and fill it with zeroes. Or just:

此代码将创建数组并用零填充它。要不就:

let arr = new Array(5).fill(0)

回答by Сергей Язев

It's 2019 and you should be using this:

现在是 2019 年,你应该使用这个:

let arr = [...Array(20)].fill(10)

let arr = [...Array(20)].fill(10)

So basically 20is the lengthor a new instantiated Array.

所以基本上20length或者一个新的实例化了Array

回答by RobG

The other answers are Ok, but a while loop seems more appropriate:

其他答案是好的,但 while 循环似乎更合适:

function setAll(array, value) {
  var i = array.length;
  while (i--) {
    array[i] = value;
  }
}

A more creative version:

更有创意的版本:

function replaceAll(array, value) {
  var re = new RegExp(value, 'g');
  return new Array(++array.length).toString().replace(/,/g, value).match(re);
}

May not work everywhere though. :-)

虽然可能无法在任何地方工作。:-)