假设我有一个这样的json数组
<>之前[" map14"、"map20"、"map21"、"map22","map23"、"map24"、"map25"、"map31"、"map32"、"map33"、"map34"、"map35"、"map36"、"map37"、"map40"、"map41"、"map42"、"map46"、"map49"、"map50")之前与这个json数组,我需要检查我传递的值是否存在,需要做一些操作或其他一些操作....
javascript代码:
function pop(e,id) {
$.getJSON( 'layoutcheck.php', { some_get_var: 1 }, function(output){
var i=0, total = output.length;
for ( i = 0; i < total; ++i ) {
if(isArray(output[i]==id)) {
// do soome stuff if the value exists in the database
}
else{
// if not exists some other operation
}
}
});
}
</script>
layoutcheck.php将从数据库中获取信息并创建一个json数组。
但是代码没有显示输出…
谢谢
isArray()
不会检查对象是否在数组中,而是检查对象是否为数组。
这意味着output[i]==id
(即true
或false
)被检查。它们总是而不是数组;这意味着你总是会去else
部分的条件
你可以试着这样写:
if(output.indexOf(id) != -1) {
// do soome stuff if the value exists in the database
}
else{
// if not exists some other operation
}
代替你的for
循环
如果你想知道id
是否在数组output
中,使用Javascript的内置indexOf()
方法:
if (output.indexOf(id) != -1) {
// do soome stuff if the value exists in the database
} else {
// if not exists some other operation
}
按照您写的方式,您将为output
中与id
不匹配的每个值执行else
子句。