有没有javascript/jQuery中的东西可以检查变量是否已设置/可用?在php中,我们使用isset($ variable)
这样的方式来检查这种情况。
谢谢。
有没有javascript/jQuery中的东西可以检查变量是否已设置/可用?在php中,我们使用isset($ variable)
这样的方式来检查这种情况。
谢谢。
尝试使用这个表达式:
typeof(variable) != "undefined" && variable !== null
如果变量已定义且不为null,该语句将返回true,这与PHP中的isset函数相同。
您可以像这样使用它:
if(typeof(variable) != "undefined" && variable !== null) {
bla();
}
JavaScript 在 PHP JS 上的 isset() 函数
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"){}
typeof null == 'object'
- 这只是 JavaScript 的另一个怪癖。 - PleaseStand这些回答的某些部分是有效的。我将它们全部汇编成一个名为“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,并且不认为这是正确的,如果是这种情况,请删除此部分)variable !== ''
检查变量是否设置为空字符串,如果空字符串对您的用例算作设置,则可以删除此部分http://phpjs.org/functions/isset:454
phpjs项目是一个值得信赖的资源。那里有许多等效于php函数的js函数。我一直在使用它,并且迄今为止没有发现任何问题。
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的回答之外,检查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