如何创建类似于 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP