for-in statement

后端 未结 4 1190
花落未央
花落未央 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:40

    In Typescript 1.5 and later, you can use for..of as opposed to for..in

    var numbers = [1, 2, 3];
    
    for (var number of numbers) {
        console.log(number);
    }
    
    0 讨论(0)
  • 2020-11-30 07:48

    The for-in statement is really there to enumerate over object properties, which is how it is implemented in TypeScript. There are some issues with using it on arrays.

    I can't speak on behalf of the TypeScript team, but I believe this is the reason for the implementation in the language.

    0 讨论(0)
  • 2020-11-30 07:50

    edit 2018: This is outdated, js and typescript now have for..of loops.
    http://www.typescriptlang.org/docs/handbook/iterators-and-generators.html


    The book "TypeScript Revealed" says

    "You can iterate through the items in an array by using either for or for..in loops as demonstrated here:

    // standard for loop
    for (var i = 0; i < actors.length; i++)
    {
      console.log(actors[i]);
    }
    
    // for..in loop
    for (var actor in actors)
    {
      console.log(actor);
    }
    

    "

    Turns out, the second loop does not pass the actors in the loop. So would say this is plain wrong. Sadly it is as above, loops are untouched by typescript.

    map and forEach often help me and are due to typescripts enhancements on function definitions more approachable, lke at the very moment:

    this.notes = arr.map(state => new Note(state));
    

    My wish list to TypeScript;

    1. Generic collections
    2. Iterators (IEnumerable, IEnumerator interfaces would be best)
    0 讨论(0)
  • 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[<any>obj] = 'this obj'
    obj[<any>undefined] = 'undefined';
    obj[<any>"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" 
    
    0 讨论(0)
提交回复
热议问题