Javascript isset 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9274674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 06:07:55  来源:igfitidea点击:

Javascript isset function

javascriptisset

提问by Tamás Pap

I created an issetfunction to check if a variable is defined and not null. Here's my code:

我创建了一个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

Any suggestion to make my function work for test 2? Thanks.

有什么建议可以让我的函数在测试 2 中工作吗?谢谢。

回答by Andrey Selitsky

You are trying to check property of an undefined object. It doesn't make any sense. You could write like this:

您正在尝试检查未定义对象的属性。这没有任何意义。你可以这样写:

alert(isset(a['not']) && isset(a['not']['existent']));

回答by Nitzan Tomer

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 beforethe call to your function...

那是行不通的,你也做不到。发生的事情是这样的:js 引擎尝试评估 a['not'] 并获得“undefined”,然后它尝试评估 undefined 的属性“existent”,你会得到那个错误。所有这些都发生调用您的函数之前......

what you can do is something like:

你可以做的是:

var isset = function(obj, props) {
    if ((typeof (obj) === 'undefined') || (obj === null))
        return false;
    else if (props && props.length > 0)
        return isset(obj[props.shift()], props);
    else
        return true;
};

then you call it like this:

然后你这样称呼它:

var a = [];

// Test 1
alert(isset(a, ['not']);
// Test 2
alert(isset(a, ['not', 'existent']));

(**this just a pseudo code, you might need to modify it a bit to actually work)

(**这只是一个伪代码,你可能需要稍微修改一下才能实际工作)

回答by Sergey Ilinsky

Test 2 will not work because "a['not']['existent']" value resolution precedes "isset" function call, and results in a runtime error.

测试 2 将不起作用,因为“a['not']['existent']”值解析在“isset”函数调用之前,并导致运行时错误。

回答by aasim

Well, You can do right this:

好吧,你可以这样做:

1) as we do in php:

1) 就像我们在 php 中所做的那样:

$vara = "abc";
$a =0;

 while(isset($vara[a]){
a++;
} 


2) as I do in javascript:

2)就像我在javascript中所做的那样:

vara = "abc";
 while (vara[a] != null){
a++;
}