JavaScript中的虚假值 [英] Falsey values in JavaScript

查看:95
本文介绍了JavaScript中的虚假值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我有一个有趣的面试问题,让我有点难过。我被问及虚假的价值观。所以undefined,NaN,null,0和一个空字符串都计算为false。在JavaScript中知道这有用的原因是什么?我唯一能想到的就是不必这样做:

I had an interesting interview question today that stumped me a little. I was asked about falsey values. So undefined, NaN, null, 0, and an empty string all evaluate to false. What is the reason this is useful to know in JavaScript? The only thing I can think of is instead of having to do this:

if (mystring === '' || mystring === undefined) { }

我可以这样做:

if (!mystring)

是这是唯一有用的应用程序吗?

Is this the only useful application?

推荐答案

您必须注意的一个危险值的一个危险问题是检查是否存在某些财产。

One dangerous issue of falsey values you have to be aware of is when checking the presence of a certain property.

假设您要测试新房产的可用性;当此属性 实际上具有 0 的值时,您可以'只需检查其可用性

Suppose you want to test for the availability of a new property; when this property can actually have a value of 0 or "", you can't simply check for its availability using

if (!someObject.someProperty)
    /* incorrectly assume that someProperty is unavailable */

在这种情况下,您必须检查它是否真的存在与否:

In this case, you must check for it being really present or not:

if (typeof someObject.someProperty == "undefined")
    /* now it's really not available */

还要注意 NaN isn等于任何东西,甚至不等于它自己( NaN!= NaN )。

Also be aware that NaN isn't equal to anything, even not to itself (NaN != NaN).

这篇关于JavaScript中的虚假值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆