将未定义的变量传递给函数时出错? [英] Error when passing undefined variable to function?
问题描述
我正在尝试创建一个可重用的函数来检查变量是否未定义。奇怪的是,当我将变量传递给函数执行代码时,它不起作用,但如果我在函数外使用相同的逻辑,它就可以工作。有没有办法让这个函数isDefined起作用?
//这个工作和返回错误
alert(typeof) sdfsdfsdfsdf!=='undefined');
//这给了一个错误,为什么?
//未捕获的ReferenceError:未定义sdfsd
函数isDefined(value){
alert(typeof value!=='undefined'&& value!== null)
}
isDefined(sdfsd);
这里的实例(检查控制台是否有错误):http://jsfiddle.net/JzJHc/
你不能用一个尚未声明的变量,除非它在 typeof
test
当你试图传递一个变量时尚未被声明为函数,即使用该未声明的变量。您会注意到错误发生在调用者,而不是 isDefined
您需要运行检查
if(typeof sdsdsd!=='undefined')
$ p在将它传递给函数之前,$ p>
。基本上这意味着你不能编写接受未声明变量的
isDefined
函数。你的函数只适用于未定义的属性(可以传递)
然而,我很好奇,你传递变量的真实情况是什么那不存在?您应该声明所有变量,它们应该已经存在。如果您声明
var sdsdsds
它将存在,其值为undefined
并且您的isDefined
函数可以正常工作。I am trying to create a reusable function that checks if a variable is undefined or not. The strange thing is that it does not work when I pass the variable to the function to execute the code, but if I use the same logic outside of the function, it works. Is there any way to get this function isDefined to work?
//THIS WORKS AND RETURN FALSE alert(typeof sdfsdfsdfsdf !== 'undefined'); //THIS GIVES AN ERROR, WHY? //Uncaught ReferenceError: sdfsd is not defined function isDefined(value) { alert(typeof value !== 'undefined' && value !== null) } isDefined(sdfsd);
Live example here (check the console for errors): http://jsfiddle.net/JzJHc/
解决方案You cannot use a variable that hasn't been declared unless it's in a
typeof
testWhen you try to pass a variable that hasn't been declared into a function, that is considered using that undeclared variable. You'll notice that the error is in the caller, not inside
isDefined
You need to run the check for
if (typeof sdsdsd !== 'undefined')
before you pass it into the function. Basically that means you can't write a
isDefined
function that accepts undeclared variables. Your function can only work for undefined properties (which are OK to pass around)However, I am curious, what is the real world case where you're passing a variable that doesn't exist? You should declare all your variables and they should exist already. Had you declared
var sdsdsds
it would exist with the value ofundefined
and yourisDefined
function would work just fine.这篇关于将未定义的变量传递给函数时出错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!