JS实现查找数组中对象的属性值是否存在示例
longzhoufeng 人气:0本文实例讲述了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.softyun.net/code/HtmlJsRun测试上述代码,可得如下运行结果:
希望本文所述对大家JavaScript程序设计有所帮助。
加载全部内容