If和Else语句都在javascript中运行

时间:2017-09-05 23:25:51

标签: javascript if-statement

运行一个简单的搜索和替换脚本,我写了一个if语句,如果字符串 AKA用户输入为空,提醒"没有字符串"但是相反,else运行的是函数,然后运行警报

KeyboardInterrupt

如果这是一个菜鸟问题,请提前抱歉,已经尝试过这里了解

2 个答案:

答案 0 :(得分:0)

应该是

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

在javascript中,null,undefined或甚至为空都是false。 希望它有所帮助。

答案 1 :(得分: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

implemented by Brian Ripley on Sep 19 2006

string is empty

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() {
		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