简体   繁体   中英

Use for loop to select dom in javascript

it's frustrating that we can't select JSON elements (or really any elements) using a similar code like this:

//An JSON object is parsed into Response beforehand
for(var count = 1; count <= Response.objCount; count ++) {
  console.log(Response.obj+count.content);
}

In the code, I want to output a JSON object like this:

{ "objCount" : 2 ,
  "obj1" : { "result" : true ,
             "content" : "blah blah 1" } ,
  "obj2" : { "result" : true ,
             "content" : "blah blah 2" } }

But no, we can't use variable as whole or part of an identifier in Javascript.. So, any suggestions on how to handle such JSON objects when I want to output each and every object?

Thank you!

If "Response" is your structure, then you can indeed do what you ask:

for(var key in Response) {
  console.log(Response[key].content);
}

You can't loop on "length" because "Response" is not an array, and plain objects don't have a "length" property.

Now, one problem is that you can't be sure that you'll get the components out in any particular order. That is, the loop above may give you "obj2" before you get "obj1". You could address that problem in a couple of ways. First, you could re-think your data structure and store it as an array. Alternatively, you could fetch the keys and sort them, and then iterate through the sorted array of property names.

var keys = Object.keys(Response);
keys.sort(function(key1, key2) {
  // comparison ...
});
for (var count = 0; count < keys.length; ++count)
  console.log(Response[keys[count]].content);

The Object.keys() function only works in newer browsers, but you can do a similar trick with a for ... in loop to pull out the property names.

edit — with your updated structure that includes an explicit property of your own for the length, you can use a plain for loop:

for (var count = 1; count <= Response.objCount; ++count)
  console.log(Response["obj" + count].content);

使用括号以属性名称作为字符串访问属性:

Response["obj" + count].content

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM