【问题标题】:How to check an undefined argument of the function? (in JavaScript) [closed]如何检查函数的未定义参数? (在 JavaScript 中)[关闭]
【发布时间】:2012-02-08 17:15:47
【问题描述】:

有一些例子:

a = ''; //string
b = 0; //number 0
b1 = 0xf; //number 15
c = (function(){}) //function function (){}
d = []; //object
e = {}; //object [object Object]
f = void(0); //undefined undefined

但是当我尝试像这样传递未定义的变量 trugth 函数时:

typeof qwerty; //undefined
function at(a){return (typeof a)+' '+a;}
at(qwerty); // ????

..i`v 收到错误“未捕获的 ReferenceError:未定义 qwerty”。 我如何(是否存在最短的方法)创建函数 isDefined(a,b) 或其他技巧来减少该表达式?:

c=(typeof a!='undefined'&&a||b)

澄清:如果定义了a - c 等于a,过度 - b,如php中的“c=@a?:b”

编辑:

function ud(_a){return typeof window[_a]==='undefined'}

a=undefined; b=3;
alert((ud('a')?4:a)+(ud('b')?5:b));​

【问题讨论】:

  • 抱歉,请问您有什么问题?
  • 帮自己一个忙,并在 google.com 上搜索“javascript 中未定义的值” - 通过阅读和尝试(尝试编辑器!)您会自己找到正确答案

标签: javascript function undefined arguments


【解决方案1】:
function isDefined(variable, dflt) {
    return typeof variable === "undefined" ? dflt : variable;
}

var c = isDefined(a, b);

【讨论】:

  • Uncaught ReferenceError: a is not defined (Google Chrome 16...)
  • 这是你调用函数的问题,你需要提供一些示例代码+所有这些示例都假设测试变量已被声明,不是这样吗?
  • jsfiddle.net/iegik/grK5X 似乎是在通过函数之前必须声明的参数,但它可以是未定义的。
  • 它失败了,因为在这种情况下,a 是未定义的并且 未声明 - 将它传递给函数的行为会失败,因为 js 无法将符号 a 解析为任何东西。将检查移动到内联而不是函数; jsfiddle.net/grK5X/3 另见stackoverflow.com/questions/8531059/…
【解决方案2】:
function def( a, b ) {
    var undef;

    return a === undef ? b : a;
}

然后:

var c = def( a, b );
// if a is defined - c equals a, otherwise b

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-29
    • 2011-09-25
    • 2019-09-22
    • 1970-01-01
    • 2010-10-29
    • 1970-01-01
    • 2021-07-14
    相关资源
    最近更新 更多