Javascript:函数参数未定义
对于变量x,让Javascript:函数参数未定义,javascript,undefined,Javascript,Undefined,对于变量x,让typeof x=='undefined' 我写了一个函数,它检查变量是否未定义 var isUndefined = function(obj){ return typeof obj == 'undefined'; }; 以下是两种情况: console.log(typeof x==“undefined”)//返回true isUndefined(x)//抛出此错误引用错误:x未定义 为什么我不能在这里传递一个未定义的变量?基本上,未定义的表示值,用户没有正式定义值。考虑你的
typeof x=='undefined'
我写了一个函数,它检查变量是否未定义
var isUndefined = function(obj){
return typeof obj == 'undefined';
};
以下是两种情况:
console.log(typeof x==“undefined”)//返回true
isUndefined(x)//抛出此错误引用错误:x未定义
为什么我不能在这里传递一个未定义的变量?基本上,未定义的表示值,用户没有正式定义值。考虑你的例子:
var isUndefined = function(obj){
return typeof obj == 'undefined';
};
因此,isUndefined()
在没有任何参数的情况下调用时,obj的值将在函数中未定义。请参见此。您必须理解未定义变量和未声明变量之间的区别
至少你会这样做:
var x; //undefined until assignment;
isUndefined(x); // returns true;
变量x
未声明,但您正在全局上下文中询问typeof
typeof x === 'undefined' // Returns true
这相当于下面的
typeof window.x === 'undefined' //True
但是下面的代码
x === undefined //Throws error
及
因为该变量从未使用任何标准JavaScript数据类型在全局范围内设置或声明
阅读博客,其中指出:
JavaScript是一种静态范围的语言,因此可以通过查看是否在封闭上下文中声明变量来了解是否声明了变量。唯一的例外是全局范围,但全局范围绑定到全局对象,因此可以通过检查全局对象上是否存在属性来检查全局上下文中是否存在变量
现在,当调用isUndefined
函数时,您将传递变量x
的引用,该变量未在父范围内声明,并在函数范围内运行代码,尝试引用x
由于x
在声明的地方是no,所以javascript解释器在运行时没有意义或值传递给isUndefined
。因此抛出引用错误,要求开发者至少声明变量,当未分配任何值时,该变量将默认设置为基元类型未定义
现在,通过显式地将x设置为基元类型,如下所示
var x; // Equivalent to window.x
或
现在JavaScript解释器知道在全局范围窗口中声明了一个名为x
的变量,并将其设置为原始数据类型。以下语句变为真
:
typeof x === 'undefined' // Returns true
x === undefined //Returns true
x in window // Returns true
isUndefined(x) // Returns true
只能使用typeof
运算符直接“检查”未声明变量的类型。您不能传递未声明的变量。如果您需要这种解决方法,您最好使用“use strict”编码>并声明所有变量。唯一的用途实际上是检查未设置的属性。请参考未声明vs未定义,但如果在没有参数的情况下调用isUndefined()
,则会声明该变量。是的,将声明该变量并将其作为isUndefined()函数堆栈的一部分。
var x = undefined; //Equivalent to window.x = undefined
typeof x === 'undefined' // Returns true
x === undefined //Returns true
x in window // Returns true
isUndefined(x) // Returns true