[英]JavaScript Return function not true result
I have an array and a function checkMember.我有一个数组和一个函数 checkMember。 I want to check, do the member have in the array?我想检查一下,该成员是否在数组中? But checkMember function only true if I call checkMember('Cody').但是 checkMember 函数只有在我调用 checkMember('Cody') 时才为真。 I don't understand.我不明白。 Please help me!请帮我!
var fe01 = [
{name: 'Giang', fee: 5, fea: 6},
{name: 'Zack', fee: 7, fea: 7},
{name: 'Henry', fee: 8, fea: 8},
{name: 'Cody', fee: 9, fea: 9}
];
function checkMember(name){
var result;
for(var i = 0; i < fe01.length; i++){
console.log(`${fe01[i].name}`)
if(fe01[i].name == name){
//console.log(true);
result = true;
} else{
//console.log(false)
result = false;
}
}
return result;
}
console.log(checkMember('Cody'));//true
console.log(checkMember('Giang'));//false
There are many ways to solve this.有很多方法可以解决这个问题。
Using for..loop
with break
statement:使用for..loop
和break
语句:
var fe01 = [ {name: 'Giang', fee: 5, fea: 6}, {name: 'Zack', fee: 7, fea: 7}, {name: 'Henry', fee: 8, fea: 8}, {name: 'Cody', fee: 9, fea: 9} ]; function checkMember(name){ var result; for(var i = 0; i < fe01.length; i++){ //console.log(`${fe01[i].name}`) if(fe01[i].name == name){ //console.log(true); result = true; break; // jump out of the loop here } else{ //console.log(false) result = false; } } return result; } console.log(checkMember('Cody'));//true console.log(checkMember('Giang'));//true
Using some()
method:使用some()
方法:
var fe01 = [ {name: 'Giang', fee: 5, fea: 6}, {name: 'Zack', fee: 7, fea: 7}, {name: 'Henry', fee: 8, fea: 8}, {name: 'Cody', fee: 9, fea: 9}]; function checkMember(search){ return fe01.some(({name}) => name == search); } console.log(checkMember('Cody'));//true console.log(checkMember('Giang'));//true console.log(checkMember('abc'));//false
This will work for you.这对你有用。
var fe01 = [
{name: 'Giang', fee: 5, fea: 6},
{name: 'Zack', fee: 7, fea: 7},
{name: 'Henry', fee: 8, fea: 8},
{name: 'Cody', fee: 9, fea: 9}
];
function checkMember(name){
return fe01.some(obj => obj.name == name)
}
console.log(checkMember('Cody'));//true
console.log(checkMember('personX'));//false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.