假设我们具有以下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