Javascript执行if和else字符串值条件

时间:2020-06-26 11:57:01

标签: javascript

如果有一个字符串是否为空"""[]",则我只有一行,然后如果不是,则从json解析为js。

console.log(a === "" || a === "[]")
console.log(typeof a)
const aLength = a === "" || a === "[]" ? 0 : JSON.parse(a).length

但是,即使再次检查是否输入了if条件,它也会为我提供来自else块的JSON解析错误。 但是有趣的是,当我在else语句中放入控制台日志时,我没有任何问题。

const aLength = a === "" || a === "[]" ? 0 : console.log('nothing') && JSON.parse(a).length

有人可以解释这种行为吗?我尝试在控制台上重新创建它,但是不能。 我的怀疑是,有一种奇怪的字符串类型会导致同时执行if和else语句。

PS:

  • 仅供参考,我正在从mongoDB加载数据。
  • 我也进行了常规的if else并遇到了相同的问题。if的评估日志为true

2 个答案:

答案 0 :(得分:2)

您可以通过以下示例了解这一点

var a = console.log("nothing");
console.log("a =", a);

// a is undefined so && operator checks for first operand in this case
// its undefined this mean its evaluted into false
// && operator evalute operands until it finds a false
a && console.log("&& nothing");

// a is undefined so || operator checks for first operand in this case
// its undefined this mean its may evaluted into true so
// it goes for next operand
// || operator evalute operands until it finds a true
a || console.log("|| nothing");

输出

nothing
a = undefined
|| nothing
undefined

以下有趣的结果。试试这个,然后粘贴到javascript控制台中。这是here

中的隐形字符
"‎"

也尝试一下

var a = "Yess‎";
console.log(a);
console.log(a === "Yess");

输出

Yess‎
false

答案 1 :(得分:1)

您的a很有可能不是空字符串"",但包含一些不可见的字符,例如BOM(字节顺序标记-"\uFEFF")或换行符({{1 }}。

最简单的解决方法可能是在比较字符串之前先"\n",从而删除开头和结尾的所有空格。

关于您观察到的.trim()行为,这是因为console.log总是返回console.log,这是虚假的。因此,undefined将永远不会调用console.log(something) && throwAnError(),因为throwAnError()短路并且未执行右侧。