简体   繁体   English

Javascript:为项目动态分配值

[英]Javascript: Dynamically assign values to items

Example: I have 3 colors and 21 numbers, and I have to dynamically create numbers and assign each number a different color. 示例:我有3种颜色和21个数字,我必须动态创建数字并为每个数字分配不同的颜色。

I did it like this: 我这样做是这样的:

var colors = ["black", "white", "red"],
  nums = [],
  count = 1;

for (var i = 0; i < 7; i++) {
  for (var c in colors) {
    nums.push([{
      id: count,
      color: colors[c]
    }]);
    count++
  }
}

I would like to know if there is a way to achieve the same thing but without going through 2 loops? 我想知道是否有一种方法可以实现相同的目的,但无需经历2个循环? Thanks 谢谢

You can accomplish the following using Math.random : 您可以使用Math.random完成以下操作:

 var colors = ["black", "white", "red"]; var nums = []; for (var i = 0; i < 21; i++) { var randomIndex = Math.floor(Math.random() * colors.length); nums.push({ id: i + 1, colors: colors[randomIndex] }); } console.log(nums); 

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

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