如果在JavaScript中未定义,则设置一个变量 [英] Set a variable if undefined in JavaScript

查看:40
本文介绍了如果在JavaScript中未定义,则设置一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以测试一个JavaScript变量,然后定义它是否为 undefined ,但是没有任何说法

I know that I can test for a JavaScript variable and then define it if it is undefined, but is there not some way of saying

var setVariable = localStorage.getItem('value') || 0;

似乎是一种更清晰的方法,而且我敢肯定我已经用其他语言看到过这种情况.

seems like a much clearer way, and I'm pretty sure I've seen this in other languages.

推荐答案

是的,它可以做到,但是严格来说,如果检索到的值为 (但不是 "0" ).

Yes, it can do that, but strictly speaking that will assign the default value if the retrieved value is falsey, as opposed to truly undefined. It would therefore not only match undefined but also null, false, 0, NaN, "" (but not "0").

如果仅当变量严格为 undefined 时才要设置为默认值,那么最安全的方法是编写:

If you want to set to default only if the variable is strictly undefined then the safest way is to write:

var x = (typeof x === 'undefined') ? your_default_value : x;

在较新的浏览器上,实际上可以安全地编写:

On newer browsers it's actually safe to write:

var x = (x === undefined) ? your_default_value : x;

但是请注意,有可能在允许声明具有定义值的名为 undefined 的变量的较旧的浏览器中进行颠覆,从而导致测试失败.

but be aware that it is possible to subvert this on older browsers where it was permitted to declare a variable named undefined that has a defined value, causing the test to fail.

这篇关于如果在JavaScript中未定义,则设置一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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