我們有一組物件,代表我們的聯系人串列中的不同人。我們有一個以名稱為引數的lookUpProfile 函式。該函式應檢查姓名是否為實際聯系人的名字。它將在控制臺上列印聯系人姓名,如果姓名與聯系人的名字匹配,則回傳 true,否則將列印 false。
我希望我的 while 回圈遍歷陣列,直到 nameCheck 等于 true 或者我大于接觸長度(也就是它到達陣列的末尾)。
似乎我的 while 回圈中的兩個條件(nameCheck == false || i < contacts.length)都不起作用。出于某種原因,即使 namecheck 等于 true 并且我的長度大于接觸長度,while 回圈也會繼續執行。
我知道您可以使用 for 回圈來實作相同的結果,而我已經做到了。但是為了學習,我想知道為什么我的while回圈不起作用。
非常感謝你。
const contacts = [
{
firstName: "Akira",
lastName: "Laine",
likes: ["Pizza", "Coding", "Brownie Points"],
},
{
firstName: "Harry",
lastName: "Potter",
likes: ["Hogwarts", "Magic", "Hagrid"],
},
{
firstName: "Sherlock",
lastName: "Holmes",
likes: ["Intriguing Cases", "Violin"],
},
];
function lookUpProfile(name) {
var nameCheck = false;
console.log(nameCheck);
var i= 0;
console.log (i);
while (nameCheck == false || i < contacts.length){
var nameOnContacts = contacts[i].firstName;
console.log(nameOnContacts);
nameCheck = nameOnContacts === name;
console.log(nameCheck);
i ;
console.log(i);
};
};
lookUpProfile("Akira");
控制臺輸出什么:
?
false
?
0
?
Akira
?
true
?
1
?
Harry
?
false
?
2
?
Sherlock
?
false
?
3
?
TypeError: contacts[i] is undefined (/index.js:28)
/index.html
uj5u.com熱心網友回復:
while只要條件為真就回圈。使用邏輯 OR ( ||) 時,只有其中一個條件為真,回圈才能繼續。你想要邏輯 AND ( &&)
const contacts = [
{
firstName: "Akira",
lastName: "Laine",
likes: ["Pizza", "Coding", "Brownie Points"],
},
{
firstName: "Harry",
lastName: "Potter",
likes: ["Hogwarts", "Magic", "Hagrid"],
},
{
firstName: "Sherlock",
lastName: "Holmes",
likes: ["Intriguing Cases", "Violin"],
},
];
function lookUpProfile(name) {
var nameCheck = false;
console.log(nameCheck);
var i= 0;
console.log (i);
while (nameCheck == false && i < contacts.length){
var nameOnContacts = contacts[i].firstName;
console.log(nameOnContacts);
nameCheck = nameOnContacts === name;
console.log(nameCheck);
i ;
console.log(i);
};
};
lookUpProfile("Akira");
編輯:如果您正在撰寫 ES6 代碼,這些是我會采取的解決方案:
如果你只是想知道名字是否已經在陣列中,Array.prototype.some可以使用該函式,如果你還想知道找到的元素的索引,你可以使用Array.prototype.findIndex:
const name = "Akira";
// function to check a single element
const firstNameMatches = (element) => element.firstName === name;
// is the name in the array at all?
const isInArray = contacts.some(firstNameMatches);
// to get the index of the found element or -1 if not found
const foundIdx = contacts.findIndex(firstNameMatches)
uj5u.com熱心網友回復:
只是添加一點額外的資訊。Douglas Crockford在他的書“Javascript: The Good Parts”中建議,使用身份運算子總是更好(避免歧義)。換句話說,最好使用“===”而不是“==”
https://medium.com/@ludico8/identity-vs-equality-battle-of-understanding-vs-758d396e922
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/413810.html
標籤:
上一篇:如何獲取每個屬性的總和值
