【问题标题】:How to loop through each entry in using For Loop JavaScript如何使用 For Loop JavaScript 遍历每个条目
【发布时间】:2020-06-02 08:18:46
【问题描述】:

我的循环功能如下

 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 打印以下内容

【问题讨论】:

  • 查看What is the difference between ( for… in ) and ( for… of ) statements in JavaScript? 和.. 你是不是忘了在你的代码sn-p 上使用索引?
  • 除了像resorces[i]这样的缺失索引,你应该用一个空字符串初始化resourceType,比如resourceType = ""
  • 您是要更改[object Object] 还是一开始就去掉undefined
  • @sam 这就是你想要达到的目标吗? example
  • 您似乎在连接对象。 (类似{}.toString() + {}.toString())这是你想要的吗?

标签: javascript arrays json for-loop


【解决方案1】:

所以,一种方法是

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);

我还创建了一个StackBlitz,其中包含有效的解决方案和您提供的 json 文件。

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-18
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 2016-07-22
    • 2022-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多