本文实例讲述了JS实现查找数组中对象的属性值是否存在。分享给大家供大家参考,具体如
本文实例讲述了JS实现查找数组中对象的属性值是否存在。分享给大家供大家参考,具体如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
var studentsArray =
[
{
"rollnumber": 1,
"name": "dj",
"subject": "physics"
},
{
"rollnumber": 2,
"name": "tanmay",
"subject": "biology"
},
{
"rollnumber": 3,
"name": "amit",
"subject": "chemistry"
}
];
function functiontofindIndexByKeyValue(arraytosearch, key, valuetosearch) {
for (var i = 0; i < arraytosearch.length; i++) {
if (arraytosearch[i][key] == valuetosearch) {
return i;
}
}
return null;
}
var index = functiontofindIndexByKeyValue(studentsArray, "rollnumber", 3);
console.log(index);
</script>
</body>
</html>
使用在线HTML/CSS/JavaScript代码运行工具:http://tools.jb51.net/code/HtmlJsRun测试上述代码,可得如下运行结果:
JS 查找 数组 对象 属性值 否存在