[英]js objects and if statements. why this code works without an else and using an else or else if statement doesn't?
我是一個非常入門的JS“開發人員”(學生),我遇到一個我無法解決的問題:當我不使用else語句時,為什么“ helperHash”中重復字母的值會增加為什么使用else語句時相同的值不會增加? 我的代碼按預期運行,但是我在理解此問題背后的邏輯時遇到了問題。
該代碼應返回一個數組,該數組的字母在給定的str中具有1個或多個重復。
function nonUniqueLetters(str){
var strToChars = str.split('');
var finalArr = [];
var helperHash = {};
for (let i = 0; i < strToChars.length; i += 1){
let char = str[i];
if (!helperHash[char]){
helperHash[char] = 0;
}
helperHash[char] += 1; //HERE! why doesn't this work if inside an else?
}
for (var key in helperHash){
if (helperHash[key] > 1){
finalArr.push(key);
}
}
return finalArr;
}
對於helperHash[char]
…
初始值為undefined
, !undefined
為true
因此將其設置為0
。
下次char
具有相同的值時, helperHash[char]
為0
且!0
也為 true
因此它將值設置為0
(該值已經是,因此沒有區別)。
代替測試該值是否為假值,可以測試它是否未定義或是否存在。
if (typeof helperHash[char] === "undefined")
要么
if (char in helperHash)
原因是這樣的if (!helperHash[char]){
以及如何在Javascript中將整數轉換為布爾值。
您將哈希的每個成員都初始化為0,這等於布爾值false,因此絕不會命中else,因為helperHash[char] === 0 === false
,因此!helperHash[char]
對於所有以0初始化的值都是true
邏輯錯誤。
if (!helperHash[char]){
// Enters here only when helperHash[char] is not set (or 0, but it is never 0)
helperHash[char] = 0;
}
// Always increment
helperHash[char] += 1;
// There is no 0 in helperHash at this point
helperHash[char] += 1
放在else
分支中不起作用: if (!helperHash[char]){
// Enters here only when helperHash[char] is not set or 0
helperHash[char] = 0;
// Still 0, will take this branch again on the next occurrence of char
} else {
// Increment only if it was already 1 or more (this never happens)
helperHash[char] += 1;
}
// Here helperHash contains only 0 for all keys
if (!helperHash[char]){
// This is the first occurrence of char, let's count it
helperHash[char] = 1;
} else {
// This is a subsequent occurrence of char, let's count it too
helperHash[char] += 1;
}
// There is no 0 in helperHash at this point
您的if
條件:
!helperHash[char]
總是評估為true
( helperHash
永遠不會包含“虛假”字符)。 因此, if
永遠不會被擊中, if
該分支的else
分支。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.