2017-02-08 148 views
2

我想比較數組中的字符串。我不知道爲什麼字符串總是不相等。字符串比較if&else語句

var person = ["Sam", "John", "Mary", "Liz"]; 
 
var firstName = prompt("enter name"); 
 
var message = ""; 
 

 
for (x in person) { 
 

 
    var firstName = person[x]; 
 

 
    if (firstName === x){ 
 
    message = "Found Person"; 
 
    } else { 
 
    message = "Nothing compares!"; 
 
    } 
 
} 
 

 
console.log(message);

+1

你有沒有'打破'循環? – Rayon

+0

您的循環將保留最後一個Liz的值,因爲for循環將執行所有的操作,而不是使用indexOf –

+3

'Array#indexOf'會更容易選擇:) – Rayon

回答

0

可以使用Array#some

var people = ["Sam", "John", "Mary", "Liz"]; 

var firstName = prompt("enter name"); 

var personFound = people.some(dude => dude === firstName); 
var message = personFound ? "Found Person" : "Nothing compares!"; 

console.log(message); 

這基本上會檢查是否some(甚至一個)dudepeople陣列中滿足dude === firstName

0

你需要的條件刪除 var firstName = person [x];

Working Example

for (var x in person) { 

// var firstName = person[x]; 

if (firstName == person[x]) 
    { 

     message = "Found Person"; 
     break; 
    } 

else 
    { 
     message = "Not Found"; 
    } 

//console.log(firstName); 

} 

console.log(message); 
+0

只搜索''Liz'',你會發現結果.. – Minksmnm

+0

嗨,它找不到Liz或任何人 – user3750366

+0

對不起,犯了一個錯誤。只是刪除休息;從其他部分 – amansoni211

0
var person = ["Sam", "John", "Mary", "Liz"]; 
var firstName = prompt("enter name"); 
var message; 
for (var x in person) { 

    console.log(firstName); 
    console.log(person[x]) 
    if (firstName === person[x]) 
    { 
     message = "Found Person"; 
    } 
    else 
    { 
     message = "Not Found"; 
    } 
console.log(message); 
} 

最佳途徑陣列可發現串或不

console.log(person.includes(firstName));//it's return true false 
0

使用這個..

var person = ["Sam", "John", "Mary", "Liz"]; 
var firstName = prompt("enter name"); 
var message = ""; 

$.each(person,function(index,name){ 
    if (firstName.toLowerCase() == name.toLowerCase()) { 
     message = "Found Person"; 
     return false; 
    } 
    else 
    { 
     message = "Nothing compares!"; 
    }  
}); 

console.log(message); 

其工作,在發佈前進行測試。 。

0

我改變了一部分代碼,希望它現在適合你。

var person = ["Sam", "John", "Mary", "Liz"]; 

var firstName = prompt("enter name"); 

var message = ""; 

for (x in person) { 

// var firstName = person[x]; 

     if (x.localeCompare(firstName)) { 

     message = "Nothing compares!"; 
    } else 
     { 

     message = "Found Person"; 

    } 

} 

console.log(message);