I have an array of empty objects like this:
var a = [ {}, {}, {}, {}, {}, {} ];
And an array of properties:
var colors = ["red", "green", "blue"];
I need to assign each color in "colors" to every element of "a" array with angular foreach. But the length of "a" array is greater than "colors". I want to assign the colors "by circle" So the result needs to be like this:
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];
});
The question: Is there some way to reset the index of foreach to start looping the "colors" array from beginning? Thanks for help
try this
var a = [ {}, {}, {}, {}, {}, {} ];
var colors = ["red", "green", "blue"];
a.forEach(function(item,key){
item.color = colors[key % colors.length];
})
console.log(a)
try javascript map
function like this
var a = [ {}, {}, {}, {}, {}, {}, {} ]; var colors = ["red", "green", "blue"]; a = a.map(function(o,i){ var color = (colors[i]) ? colors[i] : callFunc(i); o.color =color; return o; function callFunc(i){ var diff = (i - colors.length)% (colors.length) return colors[diff] } }) console.log(a)
You can simply have a counter i inside the foreach. In each iteration increment i like i++ and once it reaches the length of colors array, just reset it like i=0 and the color[i] can be used to get the color name.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.