Luc*_*nik 3 javascript arrays foreach angularjs
我有一个像这样的空对象数组:
var a = [ {}, {}, {}, {}, {}, {} ];
Run Code Online (Sandbox Code Playgroud)
以及一系列属性:
var colors = ["red", "green", "blue"];
Run Code Online (Sandbox Code Playgroud)
我需要将"颜色"中的每种颜色分配给带有角度foreach的"a"数组的每个元素.但是"a"数组的长度大于"颜色".我想要"按圈子"分配颜色所以结果必须是这样的:
var a = [
{color: "red"},
{color: "green"},
{color: "blue"},
{color: "red"},
{color: "green"},
{color: "blue"},
{color: "red"}
];
angular.forEach(a, function(elem, index) {
if (a.length > colors.length) {
// .......
}
elem.color = colors[index];
});
Run Code Online (Sandbox Code Playgroud)
问题:是否有某种方法可以重置foreach的索引,从头开始循环"colors"数组?感谢帮助
小智 6
试试这个
var a = [ {}, {}, {}, {}, {}, {} ];
var colors = ["red", "green", "blue"];
a.forEach(function(item,key){
item.color = colors[key % colors.length];
})
console.log(a)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
720 次 |
| 最近记录: |