2016-10-09 9 views
-2

私は単語をループしてperticulerの文字が存在するかどうかをチェックしますが、何らかの理由でif文の条件が機能していないかどうかを確認します。JavaScriptが条件を満たしていない場合は、

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"); 
     } 
    } 
} 
+0

あなたの答えを編集し、インデントを整理してください。 – Soviut

+6

'd'とは何ですか?どのように初期化しますか? –

+0

私は 'Main.wordArray [i] === letter'を関数の引数を使用して比較したいと思っています... – Aprillion

答えて

1

多分あなたは複雑な方法でそれをやろうとしています。 IndexOf関数を試してください。 このメソッドは、指定された値が文字列に最初に現れる位置を返します。 このメソッドは-1を返し検索する値は、例えば を発生しない場合:

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

私は、これはあなたが望むものだと思います!

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"); 
     } 
    } 
2

は、なぜあなたはJavaスクリプトはあなたに多くのオプションを提供しているこの方法でこれをやっている、あなたはどちらかのJavaScriptの文字列は、()またはのindexOf()メソッド

は、()メソッド使用してそれを行うことができます

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

Nの結果は次のようになります ザは、()メソッドは、文字列が指定されたSTの文字が含まれているか否かを判断しますリング。

このメソッドは、文字列に文字が含まれている場合はtrueを返し、そうでない場合はfalseを返します。

のindexOf()メソッド

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

Nの結果は次のようになります のindexOf()メソッドは、文字列で指定された値の最初の出現位置を返します。

検索する値が決して発生しない場合、このメソッドは-1を返します。

+0

助けてくれてありがとう、私はここにコードの何が間違っているか把握しようとしています... 。 –

+0

あなたのコードでは、dが変数のように使われているので、 "d"のような文字の書き込みにマッチさせるために、文字dとマッチさせようとしています。 –

0

あなたは何をしようとしているのか分かりませんが、OOPのアプローチを使用して文字列が存在するか、メソッド名をペルパープするかどうかを判断しようとしています。UpdateLetterは、

// 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);

:いくつかの他の文字列と...ここ

は、プロトタイプ継承constructorreplace方法を用いて達成することができる方法を実装サンプルです3210

関連する問題