If条件在javascript中比较时不起作用

if condition not working in javascript when comparing

本文关键字:比较 不起作用 javascript 条件 If      更新时间:2023-09-26

我试图通过一个单词循环并检查是否存在一个特定的字母,但由于某种原因,if语句中的条件不工作。

Main.UpdateLetter = function(letter) {
    Main.Changes = 0;
    for(i = 0 ; i < Main.word.length ; i++){
        Main.wordArray[i] = Main.word.charAt(i);
        console.log(Main.wordArray[i]); 
        if (  Main.wordArray[i]  ==  d ) {
            alert("found letter");
        } else {
            console.log("not found");
        }
    }
}

为什么要这样做JavaScript为您提供了许多选项,您可以使用JavaScript字符串包括()或indexOf()方法

包括()方法

var str = "Hello world, welcome to the universe.";
var n = str.includes("world");

n的结果将是:trueincludes()方法确定字符串是否包含指定字符串的字符。

如果字符串包含该字符,则返回true,否则返回false。

indexOf()方法

var str = "Hello world, welcome to the universe.";
var n = str.indexOf("welcome"); 

n的结果将是:13方法的作用是:返回指定值在字符串中第一次出现的位置。

如果要搜索的值从未出现,该方法返回-1。

也许你想用一种复杂的方式来做。尝试IndexOf函数。此方法返回字符串中指定值第一次出现的位置。如果要搜索的值从未出现,则此方法返回-1例如:

var x = Main.word.indexOf("d");
if( x > -1 ){
    alert("found letter at position "+x);
}
else{
    alert("Letter not found");
}

我觉得这就是你想要的!

 for (var i = 0, len = Main.word.length; i < len; i++) {
      if(Main.word.charAt(i) == "A"){
         alert("found letter");
      }else{
         console.log("not found");
      }
  }

很难弄清楚你想做什么,我怀疑你正试图使用OOP方法来查找某个字符串中是否存在字母,或者可能方法名称UpdateLetter意味着你想用其他字符串替换字母…

下面是一个示例实现,如何使用原型继承构造函数和replace方法来实现:

// object type definition (sometimes called "class")
function Main (word) {
  this.word = word;
};
Main.prototype.wordHasLetter = function(letter) {
  return this.word.indexOf(letter) !== -1;
};
Main.prototype.replaceLetterInWord = function(letter, replacement) {
  var regex = new RegExp(letter, "g");
  this.word = this.word.replace(regex, replacement);
};
// create instance of the type Main
var main = new Main("abcabc");
// sample usage of the methods
console.log("main.word is:", main.word)
if (main.wordHasLetter("a")) {
  console.log("found letter")
} else {
  console.log("not found")
}
main.replaceLetterInWord("a", "x");
console.log(main.word);