如何建立類似於 JavaScript 中 find() 方法的自定義函式?
假設我們有以下 studentId 和 studentName 的記錄,並且想檢查一個特定的學生姓名 −
const studentDetails= [ { studentId:101, studentName:"John" }, { studentId:102, studentName:"David" }, { studentId:103, studentName:"Carol" } ]
建立一個自定義函式來按姓名查詢。以下為程式碼 −
示例
const studentDetails= [ { studentId:101, studentName:"John" }, { studentId:102, studentName:"David" }, { studentId:103, studentName:"Carol" } ] function findByName(name){ var flag=true; for(var i=0;i<studentDetails.length;i++){ if(studentDetails[i].studentName==name){ flag=true; break } else{ flag=false; } } if(flag==true){ console.log("The name found="+name); } else{ console.log("The name not found="+name); } } findByName("David");
要執行以上程式,你需要使用以下命令 −
node fileName.js.
我的檔名是 demo106.js。
輸出
這將產生以下輸出 −
PS C:\Users\Amit\JavaScript-code> node demo106.js The name found=David
廣告