Giả sử chúng tôi có các bản ghi sau đây về studentId và studentName và muốn kiểm tra tên sinh viên cụ thể -
const studentDetails=
[
{
studentId:101,
studentName:"John"
},
{
studentId:102,
studentName:"David"
},
{
studentId:103,
studentName:"Carol"
}
] Tạo một chức năng tùy chỉnh để tìm theo tên. Sau đây là mã -
Ví dụ
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"); Để chạy chương trình trên, bạn cần sử dụng lệnh sau -
node fileName.js.
Đây, tên tệp của tôi là demo106.js.
Đầu ra
Điều này sẽ tạo ra kết quả sau -
PS C:\Users\Amit\JavaScript-code> node demo106.js The name found=David