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 badges1 Answer
Reset to default 11It'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
版权声明:本文标题:javascript - JSON string is treated as a literal string in loop - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742168312a2426240.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论