将未定义的参数传递给函数 - 检查变量是否存在 [英] Passing undefined parameter to function - check if variable exists

查看:88
本文介绍了将未定义的参数传递给函数 - 检查变量是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下Javascript:

Consider the following Javascript:

function getType(obj){
    return(typeof(obj))
}
alert(typeof(obj))  //alerts "undefined" correctly
alert(getType(obj))   //throws an error: ReferenceError: obj is not defined

为什么会发生这种情况?有没有解决方法?我正在尝试编写一个检查变量是否存在的函数。

Why might this be happening? Is there any workaround? I am trying to write a function which checks if a variable exists.

推荐答案

问题与typeof无关。问题是你不能将未定义的变量传递给函数。

The problem is nothing to do with typeof. The problem is that you cant pass undefined variables to functions.

function doNothing(obj){
}
doNothing(obj);

此代码也会导致错误:未捕获ReferenceError:未定义obj

因此,您在函数内编写的代码无关紧要,因为它不会被调用。错误发生在函数调用之前。

This code too results in the error: Uncaught ReferenceError: obj is not defined
So it doesn't matter what code you write inside your function, as it won't be called. The error happens before the function call.

typeof 是一个运算符,而不是函数。
这就是为什么它的行为方式与函数不同。

typeof is an operator, not a function. This is why it does not behave in the same way as functions.

这篇关于将未定义的参数传递给函数 - 检查变量是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆