SyntaxError: Unexpected Identifier (Generators in ES6)

前端 未结 2 1574
说谎
说谎 2020-12-01 13:03

I came up with this simple experiment after reading the documentation on generators from MDN:

var nodes = {
    type: \'root\',
    value: [
        { type: \         


        
2条回答
  •  春和景丽
    2020-12-01 13:43

    You've found your solution, but just for the record here is another example a little different that print the types of all nodes in the tree (I added some deepness and vars)

    var nodes = {
        type: 'root',
        value: [
            { type: 'char', value: 'a' },
            { type: 'char', value: 'b' },
            { type: 'char', value: [{type: 'int', value: 'c'}] },
        ],
    };
    
    var flattenTree = function* (root) {
        yield root.type;
        var subvalues = root.value;
        for(var i in subvalues) {
            var gen = flattenTree(subvalues[i]);
            val = gen.next();
            while(!val.done) {
                if(val.value != undefined)
                    yield val.value;
                val = gen.next();
            }
        }
    }
    
    var printTree = function() {
        console.log("begin tree");
        var generator = flattenTree(nodes);
        var next = generator.next();
        while(!next.done) {
            console.log(next);
            next = generator.next();
        }
        console.log("finish tree");
    }
    
    printTree();
    

    Outputs:

    ~/workspace/tmp$ ../node/node --harmony test-gen.js 
    begin tree
    { value: 'root', done: false }
    { value: 'char', done: false }
    { value: 'char', done: false }
    { value: 'char', done: false }
    { value: 'int', done: false }
    finish tree
    

提交回复
热议问题