[英]Assign 2 values to whole array of keys
這可能是一個愚蠢的問題,但我想對此快速解決。
我有默認的顏色數組:
foreg: defColors = ['green', 'yellow'];
我有另一列的數組
cols = ['lowest', 'low', 'medium', 'high', 'highest'];
我有像這樣的cols
數組中前三個項目的值。
filler = ['lowest': 'darkred', 'low': 'red'];
現在我想將值分配給cols
數組的其余值,並使它看起來像這樣:
filler = [lowest: 'darkred', low: 'red', medium: 'green', high: 'yellow', highest: 'green']
這可能很棘手,但我想這樣,所以如果默認顏色有2個項目,它將為col項目中的所有其余項目循環分配其值。
注意:我還有一個col項目的數組,沒有為其分配值,如下所示:
remainingKeys = ['medium', 'high', 'highest'];
您可以使用Array#forEach
遍歷remainingKeys
Array#forEach
並更新filler
對象的屬性(請注意,由於它不是數組,因此應使用大括號而不是方括號括起來)。 在這里, 余數運算符 ( %
)對於以重復模式從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.