javascript/jQuery 中有什么东西可以检查变量是否设置/可用?在 php 中,我们isset($variable)
用来检查这样的事情。
谢谢。
javascript/jQuery 中有什么东西可以检查变量是否设置/可用?在 php 中,我们isset($variable)
用来检查这样的事情。
谢谢。
试试这个表达式:
typeof(variable) != "undefined" && variable !== null
如果变量已定义且不为空,这将是正确的,这与 PHP 的 isset 的工作方式等价。
你可以像这样使用它:
if(typeof(variable) != "undefined" && variable !== null) {
bla();
}
function isset () {
// discuss at: http://phpjs.org/functions/isset
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: FremyCompany
// + improved by: Onno Marsman
// + improved by: Rafał Kukawski
// * example 1: isset( undefined, true);
// * returns 1: false
// * example 2: isset( 'Kevin van Zonneveld' );
// * returns 2: true
var a = arguments,
l = a.length,
i = 0,
undef;
if (l === 0) {
throw new Error('Empty isset');
}
while (i !== l) {
if (a[i] === undef || a[i] === null) {
return false;
}
i++;
}
return true;
}
typeof 将达到我认为的目的
if(typeof foo != "undefined"){}
如果要检查属性是否存在:hasOwnProperty是要走的路
而且由于大多数对象是其他对象的属性(最终导致该window
对象),这可以很好地检查是否已声明值。
不自然,不......但是,谷歌搜索的东西给出了这个:http ://phpjs.org/functions/isset:454
http://phpjs.org/functions/isset:454
phpjs 项目是受信任的来源。那里有很多 js 等效的 php 函数。我已经使用了很长时间,到目前为止没有发现任何问题。
每个答案的某些部分都有效。我将它们全部编译成一个函数“isset”,就像问题所问的那样,并且像在 PHP 中一样工作。
// isset helper function var isset = function(variable){ return typeof(variable) !== "undefined" && variable !== null && variable !== ''; }
这是一个如何使用它的用法示例:
var example = 'this is an example';
if(isset(example)){
console.log('the example variable has a value set');
}
这取决于您需要它的情况,但让我分解每个部分的作用:
typeof(variable) !== "undefined"
检查变量是否被定义variable !== null
检查变量是否为null(有些人明确设置为null并且不认为将其设置为null是正确的,在这种情况下,删除这部分)variable !== ''
检查变量是否设置为空字符串,如果空字符串计数为您的用例设置,则可以将其删除希望这可以帮助某人:)
问题是将未定义的变量传递给函数会导致错误。
这意味着您必须在将 typeof 作为参数传递之前运行它。
我发现这样做的最干净的方法是这样的:
function isset(v){
if(v === 'undefined'){
return false;
}
return true;
}
用法:
if(isset(typeof(varname))){
alert('is set');
} else {
alert('not set');
}
现在代码更加紧凑和可读。
如果您尝试从非实例化变量调用变量,这仍然会出错,例如:
isset(typeof(undefVar.subkey))
因此在尝试运行之前,您需要确保对象已定义:
undefVar = isset(typeof(undefVar))?undefVar:{};
除了@emil-vikström的答案之外,检查 for和 for (or )variable!=null
都是正确的。variable!==null
variable!==undefined
typeof(variable)!="undefined"
这里 :)
function isSet(iVal){
return (iVal!=="" && iVal!=null && iVal!==undefined && typeof(iVal) != "undefined") ? 1 : 0;
} // Returns 1 if set, 0 false
你可以:
if(variable||variable===0){
//Yes it is set
//do something
}
else {
//No it is not set
//Or its null
//do something else
}