2017-09-05 65 views
0

運行一個簡單的搜索和替換腳本,我寫了一條if語句,如果字符串AKA用戶輸入是空的,要警告「沒有字符串」,而是運行其他是函數,然後運行警報提前如果和其他語句都運行在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'以獲取輸入是非常易怒。爲什麼不是兩個輸入欄和一個按鈕? – tadman

+0

「*代替其他運行的是函數*」 - 你怎麼知道? – Bergi

+1

要麼你正在運行這個函數兩次,要麼你不是。通過在兩者中設置斷點來檢查您的調試器。 – tadman

回答

0

應該

if (!string || string === '') 

在javascript null,undefined或甚至爲空都是false。 希望它有幫助。

+0

空字符串也是錯誤的,所以拼寫出來是沒有意義的 - 它可以縮寫爲'如果(!string)'。但爲什麼你認爲這是OP代碼中的問題? – Bergi

+0

我試過了,但else語句仍然先運行,然後運行if語句 –

0

你的代碼工作正常。 我不知道你爲什麼認爲IF和ELSE都被執行。

當字符串爲空時,您的代碼將執行IF語句,而不會執行其他操作。不返回任何東西==返回undefined。

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