在数组 jQuery 中查找值
Find value in array jQuery
所以我需要获取数组中保存特定 id 的部分,以便我可以在其中使用其他变量。
这是我当前创建数组的代码:
<?php foreach ($list_subjects as $subject): ?>
subjects.push({
id: parseInt(<?php echo $subject['subject_id']; ?>),
subject_name: "<?php echo $subject['subject_name']; ?>",
course_type: "<?php echo $subject['course_type']; ?>",
num_videos: parseInt(<?php echo $subject['num_videos']; ?>),
subject_tag: "<?php echo $subject['subject_tags']; ?>"
});
<?php endforeach; ?>
(我知道以这种方式混合PHP不是好的做法,但请耐心等待这个问题)
这是我用来至少尝试检查值是否在数组中的代码,但它每次都返回 -1,并且数组中的值course_id IS 在数组中。
alert($.inArray(course_id, subjects.id));
为什么会这样?
$.inArray(course_id, subjects.id)
部分不起作用,因为id
是subjects
数组中对象的键(因此不是subjects
的属性)。尝试如下:
function inArrayById(array, value)
$.each(array, function(i, element) {
if(element.id === value){
return true;
}
});
return false;
}
alert( inArrayById(subjects, course_id) )
这是 Secators 函数的变体,除了它没有 jQuery 就可以工作。
function inArrayById(array, value) {
for(var i = 0; i < array.length; i++) {
if(array[i]["id"] === value) return true;
}
return false;
}