在javascript中将默认值设置为未定义的变量 [英] setting a default value to an undefined variable in javascript

查看:66
本文介绍了在javascript中将默认值设置为未定义的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

理想情况下,我希望能够写出如下内容:

Ideally I want to be able to write something like:

function a( b ) {
    b.defaultVal( 1 );
    return b;
}

这意味着如果 b 是任何定义的值, b 将保留为该值;但如果 b 未定义,则 b 将设置为参数 defaultVal(),在这种情况下 1

The intention of this is that if b is any defined value, b will remain as that value; but if b is undefined, then b will be set to the value specified in the parameter of defaultVal(), in this case 1.

这甚至可能吗?

我一直在玩弄这样的东西:

Ive been toying about with something like this:

String.prototype.defaultVal=function(valOnUndefined){
    if(typeof this==='undefined'){
        return valOnUndefined;
    }else{
        return this;
    }
};

但我没有成功将这种逻辑应用于任何变量,特别是未定义的变量。

But I'm not having any success applying this kind of logic to any variable, particularly undefined variables.

有没有人对此有任何想法?可以吗?或者我在咆哮错误的树?

Does anyone have any thoughts on this? Can it be done? Or am I barking up the wrong tree?

推荐答案

这里要学习的最重要的事情是变量是否为 undefined 默认情况下,您没有任何可用的方法。所以你需要使用一个可以对变量进行操作的方法,但不是那个变量的成员/方法

Well the most important thing to learn here is if a variable is undefined you, by default, do not have any methods available on it. So you need to use a method that can operate on the variable, but is not a member/method of that variable.

尝试像:

function defaultValue(myVar, defaultVal){
    if(typeof myVar === "undefined") myVar = defaultVal;
    return myVar;
}

你要做的就是相当于:

undefined.prototype.defaultValue = function(val) { }

......出于显而易见的原因,这不起作用。

...Which for obvious reasons, doesn't work.

这篇关于在javascript中将默认值设置为未定义的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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