admin管理员组

文章数量:1325236

I suspect this is an easy problem, but I am a bit new to js and can't find the solution.

Basically, when I pass a JSON string to a function and then attempt to iterate through the passed variable, it treats it like a literal string rather than an array.

With this function:

function build_codes_long(codes) {
   var codes_long_text = "";
   for(var i =0;i < codes.length-1;i++) {
      var code = codes[i];
      codes_long_text += "<p>" + code['id'] + " = " + code['del'] + "</p>";
   }
return codes_long_text; 
}

When I pass a JSON string to it like:

[{"id":"1","del":"0","clip":"1"},{"id":"2","del":"0","clip":"1"}]

It evaluates each character in the string, rather than each item in the array. So it loops 65 times instead of 2, returning something like:

undefined = undefined

I understand the problem with the returned values; it's the treating the array like a literal string I don't understand. Thanks!

I suspect this is an easy problem, but I am a bit new to js and can't find the solution.

Basically, when I pass a JSON string to a function and then attempt to iterate through the passed variable, it treats it like a literal string rather than an array.

With this function:

function build_codes_long(codes) {
   var codes_long_text = "";
   for(var i =0;i < codes.length-1;i++) {
      var code = codes[i];
      codes_long_text += "<p>" + code['id'] + " = " + code['del'] + "</p>";
   }
return codes_long_text; 
}

When I pass a JSON string to it like:

[{"id":"1","del":"0","clip":"1"},{"id":"2","del":"0","clip":"1"}]

It evaluates each character in the string, rather than each item in the array. So it loops 65 times instead of 2, returning something like:

undefined = undefined

I understand the problem with the returned values; it's the treating the array like a literal string I don't understand. Thanks!

Share Improve this question edited May 25, 2012 at 18:40 gen_Eric 227k42 gold badges303 silver badges342 bronze badges asked May 25, 2012 at 17:55 David FarrellDavid Farrell 1472 silver badges5 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 11

It's because you're not looping through an object; you're looping through a string and getting each letter as a result.

You need to convert the JSON string to an object first:

var myObject = JSON.parse(myJsonString);
var codesLongText = build_codes_long(myObject);

本文标签: javascriptJSON string is treated as a literal string in loopStack Overflow