如何使用For-loop JavaScript循环遍历每个条目
我的循环函数如下所示如何使用For-loop JavaScript循环遍历每个条目,javascript,arrays,json,for-loop,Javascript,Arrays,Json,For Loop,我的循环函数如下所示 var resources= jsonObj.entry; var resourceType; var i; for (i = 0; i < resources.length; i++) { resourceType += resources[i]; } console.log(resourceType) 如果我执行jsonObj.entry[0],我会得到第一个条目,因此我实现了for循环来获得所有条目,但resourceType上的cons
var resources= jsonObj.entry;
var resourceType;
var i;
for (i = 0; i < resources.length; i++) {
resourceType += resources[i];
}
console.log(resourceType)
如果我执行jsonObj.entry[0],我会得到第一个条目,因此我实现了for循环来获得所有条目,但resourceType上的console.log会打印以下内容
因此,一种方法是
var resources = jsonObj.entry;
var resourceTypeArray = [];
var resourceType = "";
for (let item = 0; item <= resources.length; item++) {
// This will remove all cases where the item doesn't exist and/or resource doesn't exist
if(resources[item] && resources[item].resource){
resourceTypeArray.push(resources[item].resource);
resourceType += JSON.stringify(resources[item].resource);
}
}
// printing out to the console the array with resources
console.info(resourceTypeArray);
// printing out to the console the string with the concatenation of the resources
console.info(resourceType);
我还创建了一个工作解决方案和您的json文件
希望有帮助。退房并。。难道你没有忘记在代码段上使用索引吗?除了缺少索引(如resources[i])之外,你还应该用空字符串初始化resourceType,如resourceType=。你想在开始时更改[object object]还是去掉未定义的?@sam这就是你想要实现的吗?您似乎正在连接对象。做一些类似{}.toString+{}.toString的事情这就是你想要的吗?