JavaScript isset 函数
我创建了一个 isset 函数来检查变量是否已定义且不为空。 这是我的代码:
isset = function(a) {
if ((typeof (a) === 'undefined') || (a === null))
return false;
else
return true;
};
var a = [];
// Test 1
alert(isset(a['not']); // Alerts FALSE -> works OK
// Test 2
alert(isset(a['not']['existent'])); // Error: Cannot read property 'existent' of undefined
有什么建议可以让我的函数适用于测试 2? 谢谢。
I created an isset function to check if a variable is defined and not null.
Here's my code:
isset = function(a) {
if ((typeof (a) === 'undefined') || (a === null))
return false;
else
return true;
};
var a = [];
// Test 1
alert(isset(a['not']); // Alerts FALSE -> works OK
// Test 2
alert(isset(a['not']['existent'])); // Error: Cannot read property 'existent' of undefined
Any suggestion to make my function work for test 2?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您正在尝试检查未定义对象的属性。这没有任何意义。你可以这样写:
You are trying to check property of an undefined object. It doesn't make any sense. You could write like this:
那是行不通的,你也不能让它行得通。
发生的事情是这样的:
js 引擎尝试评估 ['not'] 并得到“未定义”,然后尝试评估未定义的属性“存在”,然后您会收到该错误。
所有这些都发生在调用您的函数之前...
您可以做的是这样的:
然后您像这样调用它:
(**这只是一个伪代码,您可能需要修改它实际工作一点)
that won't work, and you can't make it work.
what happens is this:
the js engine tries to evaluate a['not'] and get's "undefined", then it tries to evaluate the property 'existent' of the undefined and you get that error.
all of that happens before the call to your function...
what you can do is something like:
then you call it like this:
(**this just a pseudo code, you might need to modify it a bit to actually work)
测试 2 将不起作用,因为“a['not']['existent']”值解析先于“isset”函数调用,并导致运行时错误。
Test 2 will not work because "a['not']['existent']" value resolution precedes "isset" function call, and results in a runtime error.
好吧,你可以这样做:
1)就像我们在 php 中所做的那样:
2)就像我在 javascript 中所做的那样:
Well, You can do right this:
1) as we do in php:
2) as I do in javascript: