2017-09-05 16 views
0

単純な検索と置換スクリプトを実行していて、文字列AKAユーザー入力が空であれば、関数であり、これはnoobの質問されている場合、アラートが事前に申し訳ありませんIfとElseステートメントの両方がJavaScriptで実行されています

let str = ''; // Testing if statement 
let findWord = prompt('what word do you want to find'); 
let replaceWith = prompt('replace with that new word'); 

const searchAndReplace = (string, oldWord, newWord) => { 
     if (string == '') { // should it be '', or null, or undefined? 
      alert('no msg') 
     } else { 
      return string.split(oldWord.toLowerCase()).join(newWord.toLowerCase()); 
     } 
} 

let newString = searchAndReplace(str, findWord, replaceWith); 
console.log(newString); 

を実行し、すでにここを

+0

、入力を取得するには、 'prompt'を使用してはかなり無愛想です。なぜ2つの入力フィールドとボタンはありませんか? – tadman

+0

"*代わりにelse関数が実行されます*" - あなたはどのように知っていますか? – Bergi

+1

この機能を2回実行しているか、そうでないかのどちらかです。両方にブレークポイントを設定して、デバッガに確認してください。 – tadman

答えて

0

を探してみました、それは

if (!string || string === '') 
でなければなりません

のjavascriptがnull、未定義、または空でさえもfalseです。 助けてくれることを願っています。

+0

空文字列もfalseであるので、それを綴るのは無意味です。 if(!string) '。しかし、なぜこれがOPコードの問題だとお考えですか? – Bergi

+0

私は試しましたが、else文が最初に実行されてからif文が実行されます –

0

コードは正常に動作しています。 IFとELSEの両方が実行されたと思われる理由はわかりません。

文字列が空の場合、コードはIF文を実行し、その他は実行しません。何も返さない==は未定義です。注意点としては

function Test1() { 
    console.log("I return undefined, not null"); 
} 

var test1 = Test1(); 
console.log("Test 1 is ? ", test1); // Test 1 is ? undefined 

function Test2() { 
    console.log("I return string"); 
    return "test2-string"; 
} 

var test2 = Test2(); 
console.log("Test 2 is ? ", test2); // Test 2 is ? test2-string 

string is empty

Else statement only

let str = ''; // Testing if statement 
 
let findWord = prompt('what word do you want to find'); 
 
let replaceWith = prompt('replace with that new word'); 
 

 
const searchAndReplace = (string, oldWord, newWord) => { 
 
     // should it be '', or null, or undefined? 
 
     console.log("input value: ", string, oldWord, newWord); 
 
     if (string == '') { 
 
      console.log("IF it's empty"); 
 
      alert('no msg'); 
 
     } else { 
 
      console.log("ELSE string is not empty"); 
 
      return string.split(oldWord.toLowerCase()).join(newWord.toLowerCase()); 
 
     } 
 
}; 
 

 
let newString = searchAndReplace(str, findWord, replaceWith); 
 
console.log("newString: ", newString); 
 

 

 
console.log("========================="); 
 

 

 
function Test1() { 
 
\t \t console.log("I return undefined, not null"); 
 
\t } 
 

 
\t var test1 = Test1(); 
 
\t console.log("Test 1 is ? ", test1); // Test 1 is ? undefined 
 

 
\t function Test2() { 
 
\t \t console.log("I return string"); 
 
\t return "test2-string"; 
 
\t } 
 

 
\t var test2 = Test2(); 
 
\t console.log("Test 2 is ? ", test2); // Test 2 is ? test2-string

関連する問題