javascript javascript中类型的默认值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14603106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 22:04:41  来源:igfitidea点击:

Default value of a type in javascript

javascripttypesdefault-value

提问by amrk7

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

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

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

回答by Jordan Gray

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 defaultoperator in C#.

这两个答案都正确地指出 JavaScript 中变量的默认(未分配)值是undefined,但都没有解决您似乎在寻找的问题——相当于defaultC# 中的运算符。

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

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

  • the name of a JS primitive;
  • any valid production of the typeofoperator; or
  • a function name either in the thisvalue it is called with or its local scope1
  • JS 原语的名称;
  • typeof经营者的任何有效生产;或者
  • 一个函数名,要么是在this它被调用的值中,要么是它的本地作用域 1

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 {}; }
}

You can call it like this:

你可以这样称呼它:

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


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

不幸的是,JStypeof操作符对于我们的目的来说可能有点……无名。例如,typeof null === 'object', 和typeof [] === 'object',这可能不是您想要的。

To work around this, here's a function that returns the result of calling typeofon a value unlessthe result is 'object', in which case it will return 'null'if the value is nulland obj.constructor.nameotherwise (with 'object'as the fallback value if all else fails):

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

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';
}

And now we can have:

现在我们可以有:

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!)

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.

我怀疑这与您要寻找的东西尽可能接近。另外,为了避免任何批评:上面的 eval 的使用可能看起来有点脏,但它是从当前作用域中获取命名值的唯一方法。



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

1 该函数不能调用在另一个作用域中实例化的构造函数;相反,我已经可以通过this绑定到一个包含它可能引用的任何此类构造函数的对象来调用它:

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.

如果你不这样做,它只会退回到返回一个新对象。

回答by Praveen Kumar Purushothaman

I don't understand why do you ask such a question. Anyways, the default value of a variable in JavaScript is nullor undefined.

我不明白你为什么问这样的问题。无论如何,JavaScript 中变量的默认值是nullor undefined

For learning purposes, I took this from WikiBooks JavaScript/Variables and Types:

出于学习目的,我从 WikiBooks JavaScript/Variables and Types 中获取了这个:

Variables are commonly explicitly declared by the var statement, as shown below:

var c;

The above variable is created, but has the default value of undefined. To be of value, the variable needs to be initialized:

var c = 0;

After being declared, a variable may be assigned a new value which will replace the old one:

c = 1;

But make sure to declare a variable with var before (or while) assigning to it; otherwise you will create a "scope bug."

变量通常由 var 语句显式声明,如下所示:

var c;

上述变量已创建,但具有默认值undefined。为了有价值,变量需要被初始化:

var c = 0;

声明后,可以为变量分配一个新值,该值将替换旧值:

c = 1;

但是请确保在分配给它之前(或同时)使用 var 声明一个变量;否则,您将创建一个“范围错误”。

And now, when you ask why the value is not 0, it is because, even nullor undefinedare values, which are not defined. Not defined is different from being defined and empty. It might return 0, when the value is declared and not defined.

而现在,当你问为什么值不是0,这是因为,即使null或者undefined是价值观,这是没有定义的。未定义与已定义和空的不同。0当值被声明但未定义时,它可能会返回。

回答by Denys Séguret

The default value of any variable in javascript is undefined. You can also get it as

javascript 中任何变量的默认值都是undefined. 你也可以把它作为

var defaultValue = void 0;