简体   繁体   English

为整个键数组分配2个值

[英]Assign 2 values to whole array of keys

This might be the silly question but i want quick solution for this. 这可能是一个愚蠢的问题,但我想对此快速解决。

I have default colors array: 我有默认的颜色数组:

foreg : defColors = ['green', 'yellow']; foreg: defColors = ['green', 'yellow'];

and I have another array of column 我有另一列的数组

cols = ['lowest', 'low', 'medium', 'high', 'highest'];

I have the the values for first three items in cols array like this. 我有像这样的cols数组中前三个项目的值。

filler = ['lowest': 'darkred', 'low': 'red'];

And now i want to assign values to rest of value of cols array and make it look like this: 现在我想将值分配给cols数组的其余值,并使它看起来像这样:

filler = [lowest: 'darkred', low: 'red', medium: 'green', high: 'yellow', highest: 'green']

This might be tricky but I want exactly like this, so if default colors has 2 items it assign its value in loop for all remaining items from col items. 这可能很棘手,但我想这样,所以如果默认颜色有2个项目,它将为col项目中的所有其余项目循环分配其值。

Note: I also have an array for col items that doesn't have its value assigned like this: 注意:我还有一个col项目的数组,没有为其分配值,如下所示:

remainingKeys = ['medium', 'high', 'highest'];

You can use Array#forEach to iterate over your remainingKeys and update the properties of the filler object (note that, since it is not an array, it should be enclosed in curly brackets rather than square ones). 您可以使用Array#forEach遍历remainingKeys Array#forEach并更新filler对象的属性(请注意,由于它不是数组,因此应使用大括号而不是方括号括起来)。 The remainder operator ( % ) is useful here for selecting a color from your defColors array in a repeating pattern. 在这里, 余数运算符% )对于以重复模式从defColors数组中选择颜色很有用。

 var defColors = ['green', 'yellow'] var cols = ['lowest', 'low', 'medium', 'high', 'highest'] var filler = {'lowest': 'darkred', 'low': 'red'} var remainingKeys = ['medium', 'high', 'highest']; remainingKeys.forEach(function (key, i) { this[key] = defColors[i % defColors.length] }, filler) console.log(filler) 
 .as-console-wrapper { min-height: 100%; } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM