javascript中类型的默认值 [英] Default value of a type in javascript

查看:115
本文介绍了javascript中类型的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript中是否有一个函数返回传递给它的类型名称的默认值?例如:

Is there a function in JavaScript that returns the default value for a type name that is passed to it? For example:

var defaultValue = built_in_getDefaultValue("number");
console.log(defaultValue); // Logs the number 0 to the console.


推荐答案

两个答案都正确地注明了默认值(未分配) )JavaScript中变量的值是 undefined ,但是它们都没有解决你想要寻找的东西 - 相当于例如C#中的默认运算符。

Both of the answers correctly note that the default (unassigned) value of a variable in JavaScript is undefined, but neither addresses what you seem to be looking for—an equivalent of e.g. the default operator in C#.

幸运的是,JavaScript有一个非常简单的类型系统:一切都不是一个六种原始类型(ES5中的五种)是一个对象,可以通过它的构造函数来调用。以下函数,给定一个字符串表示

Fortunately, JavaScript has a very simple type system: everything that isn't one of the six primitive types (five in ES5) is an object, and can be called via its constructor. The following function, given a string representing


  • JS原语的名称;

  • 任何有效生产 typeof 运算符;或者

  • 函数名称在值中调用它或其本地范围¹

  • the name of a JS primitive;
  • any valid production of the typeof operator; or
  • a function name either in the this value it is called with or its local scope¹

将对默认值产生合理解释:

will produce a reasonable interpretation of a "default" value:

function defaultVal(type) {
    if (typeof type !== 'string') throw new TypeError('Type must be a string.');

    // Handle simple types (primitives and plain function/object)
    switch (type) {
        case 'boolean'   : return false;
        case 'function'  : return function () {};
        case 'null'      : return null;
        case 'number'    : return 0;
        case 'object'    : return {};
        case 'string'    : return "";
        case 'symbol'    : return Symbol();
        case 'undefined' : return void 0;
    }

    try {
        // Look for constructor in this or current scope
        var ctor = typeof this[type] === 'function'
                   ? this[type]
                   : eval(type);

        return new ctor;

    // Constructor not found, return new object
    } catch (e) { return {}; }
}

您可以这样称呼:

defaultVal( typeof 1 ); // -> 0
defaultVal( 'number' ); // -> 0
defaultVal( 'object' ); // -> {}
defaultVal( 'RegExp' ); // -> /(?:)/






不幸的是,JS typeof 运算符可能有点......为我们的目的而变形。例如, typeof null ==='object' typeof [] ==='object',其中可能不是你想要的。


Unfortunately, the JS typeof operator may be a bit… anameic for our purposes. For example, typeof null === 'object', and typeof [] === 'object', which probably isn't what you want.

要解决这个问题,这里有一个函数返回调用 typeof 对值除非结果为'object',在这种情况下,如果值为'null' > null 和 obj.constructor.name 否则(以'object'作为后备值如果所有其他方法都失败了):

To work around this, here's a function that returns the result of calling typeof on a value unless the result is 'object', in which case it will return 'null' if the value is null and obj.constructor.name otherwise (with 'object' as the fallback value if all else fails):

function getType(obj) {
    var type = typeof obj;

    if (type !== 'object') return type; // primitive or function
    if (obj === null) return 'null';    // null

    // Everything else, check for a constructor
    var ctor = obj.constructor;
    var name = typeof ctor === 'function' && ctor.name;

    return typeof name === 'string' && name.length > 0 ? name : 'object';
}

现在我们可以:

defaultVal( getType( 1234 ) );  // -> 0
defaultVal( getType( [99] ) );  // -> []
defaultVal( getType( 'ab' ) );  // -> ""
defaultVal( getType( null ) );  // -> null   (Not possible with typeof!)
defaultVal( getType( /.*/ ) );  // -> /(?:)/ (Not possible with typeof!)

function T () {}
defaultVal( getType( new T ) ); // -> T {}   (Not possible with typeof!)

我怀疑这跟你的情况差不多寻找你会得到的。另外,要避免任何批评:上面使用eval可能看起来有点脏,但这是从当前范围获取命名值的唯一方法。

I suspect this is as close to what you're looking for as you're going to get. Also, to head off any criticism: the use of eval above might seem a bit dirty, but it's the only way to get a named value from the current scope.

¹此函数无法调用在另一个范围内实例化的构造函数;相反,我已经可以用这个来调用它,它绑定到一个对象,该对象包含它可能引用的任何这样的构造函数:

¹ This function can't call a constructor instantiated in another scope; instead, I've made it possible to call it with this bound to an object containing any such constructors it may reference:

function innerScopeCtor() {
    function T () {}

    return defaultVal.call( { T : T }, 'T' );
}

innerScopeCtor(); // T {}

如果你不这样做,它将会回归到新对象。

If you don't do this, it will just fall back to returning a new object.

这篇关于javascript中类型的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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