[英]For loop doesn't work in array (Javascript, Angular 2)
I have an array that contains cameras specifications, the problem occurs when I try to run a for loop to get the elements.我有一个包含相机规格的数组,当我尝试运行 for 循环来获取元素时会出现问题。
Here is the content of my array :这是我的数组的内容:
I tried all different types of for loops like forEach, basic for loop with increment or for ( let item of myArray
)我尝试了所有不同类型的 for 循环,如 forEach、带增量或 for 的基本 for 循环(
let item of myArray
)
For loop doesn't run and I have no return of the element in the array. For 循环没有运行,我没有返回数组中的元素。
for (let id in elements) {
if (typeof elements[id].brands !== 'undefined') {
delete this.items;
let itemsArray = [];
for (let elementData of elements[id].brands) {
this.http.get("assets/data/" + elementData + "Reflex.json").map(res => res.json()).subscribe(data => {
Array.prototype.push.apply(itemsArray, data);
});
}
this.items = itemsArray;
}
if (typeof elements[id].sensorSize !== 'undefined') {
}
}
( this.items
is the array that you can see on the top (I use Angular2)). (
this.items
是您可以在顶部看到的数组(我使用的是 Angular2))。
Try this code, it will iterate on the array itself and return all items in it as objects in the inline function.试试这段代码,它会迭代数组本身,并将其中的所有项目作为内联函数中的对象返回。
this.items.forEach( function (item)
{
item.xxx=11;
} );
this.http.get("assets/data/" + elementData + "Reflex.json").map(res => res.json()).subscribe(data => {
Array.prototype.push.apply(itemsArray, data);
});
This call is the problem.It is asynchronous .这个调用有问题。它是异步的。
The for loop will not wait for the response to push data into itemArray
. for 循环不会等待响应将数据推送到
itemArray
。 A rough way to get the array is:获取数组的粗略方法是:
this.http.get("assets/data/" + elementData + "Reflex.json").map(res => res.json()).subscribe(data => {
Array.prototype.push.apply(this.items, data);//make sure this.items is set to empty previous to call
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.