for-in statement

后端 未结 4 1209
花落未央
花落未央 2020-11-30 07:07

TypeScript docs say nothing about loop like for or for-in. From playing with the language it seems that only any or string

4条回答
  •  甜味超标
    2020-11-30 07:56

    TypeScript isn't giving you a gun to shoot yourself in the foot with.

    The iterator variable is a string because it is a string, full stop. Observe:

    var obj = {};
    obj['0'] = 'quote zero quote';
    obj[0.0] = 'zero point zero';
    obj['[object Object]'] = 'literal string "[object Object]"';
    obj[obj] = 'this obj'
    obj[undefined] = 'undefined';
    obj["undefined"] = 'the literal string "undefined"';
    
    for(var key in obj) {
        console.log('Type: ' + typeof key);
        console.log(key + ' => ' + obj[key]);
    }
    

    How many key/value pairs are in obj now? 6, more or less? No, 3, and all of the keys are strings:

    Type: string
    0 => zero point zero
    Type: string
    [object Object] => this obj; 
    Type: string
    undefined => the literal string "undefined" 
    

提交回复
热议问题