簡體   English   中英

js對象和if語句。 為什么此代碼在沒有else且不使用else或else if語句的情況下有效?

[英]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!undefinedtrue因此將其設置為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]

總是評估為truehelperHash永遠不會包含“虛假”字符)。 因此, if永遠不會被擊中, if該分支的else分支。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM