簡體   English   中英

獲得未定義但我想在 for 循環中使用 else 語句並顯示“不存在”。 請幫我解決

[英]Getting undefined but i would like to use else statement inside for loop and display 'not exist' instead. please help me to fix

我如何在下面使用 else 語句,想將 undefined 替換為“不存在”,嘗試但不起作用。 程序:檢查給定字符串是否包含指定字符的 2 到 4 個數字

 function check_char(x, y) { for (var j = 0; j < y.length; j++) { var d = y[j]; } for (var i = 1; i <= 3; i++) { data = x[i] console.log(data) if (data == d) { return d + " exist"; } } } document.write(check_char("Python", "y") + "<br>"); document.write(check_char("JavaScript", "a") + "<br>"); document.write(check_char("Console", "o") + "<br>"); document.write(check_char("Console", "C") + "<br>"); document.write(check_char("Console", "e") + "<br>"); document.write(check_char("JavaScript", "S") + "<br>");

**output:** 
y exist
a exist
o exist
undefined
undefined
undefined

嚴格來說,你不需要else 記錄字符在字符串中出現的次數。 如果計數 >= 2 和 <= 4 返回“存在”,否則只返回“不存在”。

您應該避免使用document.write 此示例有一個額外的 function,它使用從checkChar function 返回的字符串創建一些 HTML ,然后使用insertAdjacentHML將其添加到頁面。

 function checkChar(str, char) { // Initialise the count let count = 0; // Loop over the string - if the // letter in the iteration is the same as // the character increment the count for (const letter of str) { if (letter === char) ++count; } // If the count is within bounds return "exists" if (count >=2 && count <=4) { return `<span class="red">${char}</span> exists`; } // Otherwise return "does not exist" return `<span class="red">${char}</span> does not exist`; } function write(str) { // Create an HTML paragraph string with the string // returned from `checkChar`, and then add that // to the page const para = `<p>${str}</p>`; document.body.insertAdjacentHTML('beforeend', para); } write(checkChar('Python', 'y')); write(checkChar('JavaScript', 'a')); write(checkChar('Console', 'o')); write(checkChar('Console', 'C')); write(checkChar('Console', 'e')); write(checkChar('JavaScript', 'S'));
 .red { color: red; }

嘗試這個,

function check_char(x, y) {
  for (var j = 0; j < y.length; j++) {
    var d = y[j];
  }
  for (var i = 1; i <= 3; i++) {
    data = x[i]
    console.log(data)
    if (data == d) {
      return d + " exist";
    }
  }
  return 'not exist';
}

暫無
暫無

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

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