【问题标题】:what is interpreted by javascript when we do if({ })? [duplicate]当我们执行 if({ }) 时,javascript 会解释什么? [复制]
【发布时间】:2018-12-18 05:21:18
【问题描述】:

在面试的时候我很困惑

  1. if({}) console.log("hello")
  2. if([]) console.log("hello")
  3. if(' ') console.log("hello")
  4. if('') console.log("hello")

我知道前三个会打印 hello ,但我不知道评估的依据是什么。

甚至我也想知道一些网站或 URL,我可以从中获得这些棘手的问题和解决方案

【问题讨论】:

  • 搜索"JavaScript truthy value" - 在if (expr) stmt; 中,当且仅当expr 评估为这样的“真实值”时才会执行stmt。

标签: javascript if-statement


【解决方案1】:

''、null、undefined 和 0 是假的例子,其他都是真。

if({})
  console.log("Empty Object is truthy");
  
if([])
  console.log("Empty array is truthy");
  
if(' ')
  console.log("Space is truthy");
  
if(!'')
  console.log("Empty string is falsey");

if(!null)
  console.log("null is falsey");

if(!undefined)
  console.log("undefined is falsey");

if(!0)
  console.log("Zero is falsey");

【讨论】:

  • 感谢阿德里安的回答,但还有一件事,如果未定义为假,那么当我们创建一个空数组时,它也是未定义的。那么,当时它如何评估为真
  • 空数组不是未定义的,它是一个数组对象的实例,具有长度 === 0 等属性。
  • 但是当我们声明像 var x = [] 或 var x= new Array() 这样的数组时,它给出了 undefined
  • 你是什么意思它给 undefined?
  • 抱歉阿德里安提出了这么多疑问,但这是最后一个。当我在控制台窗口中输入 var x = [] 后按回车键给出未定义,当我写 x:Array = [] 时它没有给出未定义它给出空数组 []。为什么会这样?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-18
  • 2018-05-03
  • 2018-08-19
  • 1970-01-01
  • 1970-01-01
  • 2020-12-31
  • 2022-07-19
相关资源
最近更新 更多