2014-09-24 70 views
2

if (typeof (location.x != null) {的Javascript如果变量不是空

使用我碰到下列错误上面:Uncaught TypeError: Cannot read property 'x' of null

我试图console.log(location.x)这将导致一个例子与null

+0

请问您在哪里运行此代码?由于'window.location',使用'location'的 – Sprottenwels 2014-09-24 14:13:43

+3

往往是一个错误的变量名称。一个错过'var'和你的“truthy”检查将是真实的。 – epascarello 2014-09-24 14:15:23

+0

@ epascarello-那么为什么它* null *?顺便说一句,[* typeof *](http://ecma-international.org/ecma-262/5.1/#sec-11.4.3)总是返回一个永远不会是'== null'的字符串。 – RobG 2014-09-24 14:16:48

回答

7
if (location && location.x) { 

}  
+1

希望x不是一个虚假的价值。 – epascarello 2014-09-24 14:19:15

+0

在这种情况下,您使用location.x!= undefined条件if语句 – Fabio 2014-09-24 14:23:15

+0

'typeof myVariable!=='undefined'更安全IMO - 没有恐怖分子jQuery插件可以在您使用typeof时重新定义'undefined'。 – 2014-09-24 16:56:53

2

你可以这样做:

if (location && location.x) { 

} 
+0

依然有'Uncaught TypeError:无法读取属性'x'null'的结果 – ngplayground 2014-09-24 14:13:58

+1

做了编辑 - 现在应该很好。 – tymeJV 2014-09-24 14:14:15

+0

希望x不是一个虚假的价值。 – epascarello 2014-09-24 14:19:37

1

由于您的位置变量为空,无法达到x属性