jQuery“TypeError:无效的'in'操作数a”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24429957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery "TypeError: invalid 'in' operand a"
提问by Mariano
I have the following json array returning from an ajax call:
我有以下 json 数组从 ajax 调用返回:
{"err":"err_type","fields":["field1","field2"]}
{"err":"err_type","fields":["field1","field2"]}
when tryin to print it out with this function:
当尝试使用此功能打印出来时:
$.each(data.fields, function (i, field) {
console.log(field);
$.each(field, function (j, f) {
$('[name="'+f+'"]').addClass('form_err');
console.log(f);
});
});
i get this:
我明白了:
data1
TypeError: invalid 'in' operand a
...turn function(b){return db(a,b).length>0}}),contains:fb(function(a){return funct...
and so i can't figure out how to use this array! Anyone have any idea?
所以我不知道如何使用这个数组!任何人有任何想法?
回答by Anton
You are iterating a string, you don't need two .each() functions
您正在迭代一个字符串,您不需要两个 .each() 函数
$.each(data.fields, function (i, field) {
$('[name="'+field+'"]').addClass('form_err');
console.log(field);
});
回答by Waweru wa Kamau
Remember to add dataType: 'json';
so that it can be looped as an array and not a string.
请记住添加,dataType: 'json';
以便它可以作为数组而不是字符串循环。
回答by Jai
You don't need another loopin $.each()
:
你不需要另一个循环$.each()
:
$.each(data.fields, function (i, field) {
console.log(field);
$('[name="'+field+'"]').addClass('form_err');
});
data.fields
is an array which contains strings
only, so you don't need to loopin again. You just need to loopin only when if it would be another array object with {key:value}
pairs.
data.fields
是一个strings
只包含的数组,所以你不需要再次循环。只有当它是另一个{key:value}
成对的数组对象时,您才需要循环。
回答by Adrien LUCAS
In your main loop, the "field" var is not an array, so you can't use "each" on it.
在您的主循环中,“字段”变量不是数组,因此您不能在其上使用“每个”。