哪种检查变量是否已初始化的方法更好/正确?(假设变量可以保存任何内容(字符串、int、对象、函数等))
if (elem) { // or !elem
or
if (typeof elem !== 'undefined') {
or
if (elem != null) {
哪种检查变量是否已初始化的方法更好/正确?(假设变量可以保存任何内容(字符串、int、对象、函数等))
if (elem) { // or !elem
or
if (typeof elem !== 'undefined') {
or
if (elem != null) {
当前回答
我想要类似的东西:一个检查变量是否有有用值的函数,其中0是有用的,但空字符串、数组和对象不是(对于我的应用程序)。基于各种答案和评论,我提出了下面定义和测试的isSet()函数;对于测试值的前一半返回true,对于第二部分返回false,这正是我想要和需要的:
let fn = [1234, "1234", 0, "0", [1,2], {name: "number"}, "", [], {}, null, NaN, undefined]
console.log(fn)
const isSet = (val) => {
switch (typeof val) {
case 'number': return !isNaN(val); break; // as long as it is a number other than NaN....
case 'string': return val.length > 0; break;
case 'undefined': return false; break;
case 'object':
if (val === null) return false;
else return Object.keys(val).length > 0;
break;
}
}
for (index in fn) {
const item = fn[index];
console.log(`ind: ${index}; ${typeof item}; ${isSet(item)}`)
}
结果(在节点v16.16.0下):
[
1234,
'1234',
0,
'0',
[ 1, 2 ],
{ name: 'number' },
'',
[],
{},
null,
NaN,
undefined
]
ind: 0; number; true
ind: 1; string; true
ind: 2; number; true
ind: 3; string; true
ind: 4; object; true
ind: 5; object; true
ind: 6; string; false
ind: 7; object; false
ind: 8; object; false
ind: 9; object; false
ind: 10; number; false
ind: 11; undefined; false
其他回答
if (typeof console != "undefined") {
...
}
或者更好
if ((typeof console == "object") && (typeof console.profile == "function")) {
console.profile(f.constructor);
}
适用于所有浏览器
在问题中概述的特定情况下,
typeof window.console === "undefined"
与相同
window.console === undefined
我更喜欢后者,因为它更短。
请注意,我们只在全局范围内查找控制台(这是所有浏览器中的窗口对象)。在这种特殊情况下,这是可取的。我们不希望在其他地方定义控制台。
@BrianKelley在他出色的回答中解释了技术细节。我只是补充了不足的结论,并将其消化为更容易阅读的内容。
在许多情况下,使用:
if (elem) { // or !elem
会为你做这件事的!。。。这将检查以下情况:
undefined:如果值未定义且未定义null:如果它为null,例如,如果DOM元素不存在。。。空字符串:“”0:数字零NaN:不是数字假的
所以它将涵盖所有的情况,但我们也希望涵盖一些奇怪的情况,例如,一个带空格的字符串,比如这个“”,这将在javascript中定义,因为它在字符串中有空格。。。例如,在本例中,您使用trim()再添加一个检查,例如:
if(elem) {
if(typeof elem === 'string' && elem.trim()) {
///
此外,这些检查仅针对值,因为对象和数组在Javascript中的工作方式不同,所以空数组[]和空对象{}始终为true。
我创建了下面的图像,以显示答案的简要说明:
if (variable === undefined) {}
工作正常,只检查未定义。
我的首选是typeof(elem)!='未定义'&&elem!=无效的
无论您选择什么,请考虑将检查放入这样的函数中
function existy (x) {
return typeof (x) != 'undefined' && x != null;
}
如果您不知道变量已声明,请继续使用typeof(x)!='未定义'&&x!=无效的
如果您知道变量已声明但可能不存在,可以使用
existy(elem) && doSomething(elem);
您正在检查的变量有时可能是嵌套属性。您可以使用prop | |{}来检查问题属性的存在性:
var exists = ((((existy(myObj).prop1||{}).prop2||{}).prop3||{})[1]||{}).prop4;
在每个属性之后,使用(…“| |{}”).nexPro,以便丢失的属性不会引发错误。
或者,您可以使用existy,如existy(o)&&exist(o.p)&&existiny(o.p.q)&&doSomething(o.p.q)