1

如果我想按顺序打印所有音高,以使左边先出现,然后右边出现,我该如何遍历以下内容。对于以下第一段代码;答案应该是 a4、b4、c4、d4。我怎样才能以编程方式实现这一目标?

var melody2_mus = 
    { tag: 'seq',
      left: 
       { tag: 'seq',
         left: { tag: 'note', pitch: 'a4', dur: 250 },
         right: { tag: 'note', pitch: 'b4', dur: 250 } },
      right:
       { tag: 'seq',
         left: { tag: 'note', pitch: 'c4', dur: 500 },
         right: { tag: 'note', pitch: 'd4', dur: 500 } } }

另一个例子:

 var melody2_mus = 
        { tag: 'seq',
          left: { tag: 'note', pitch: 'b4', dur: 250 } },
          right:
           { tag: 'seq',
             left: { tag: 'note', pitch: 'c4', dur: 500 },
             right: { tag: 'note', pitch: 'd4', dur: 500 } } }

应该打印 b4, c4, d4

谢谢

4

2 回答 2

7

递归函数将是最简单的:

function traverse(obj) {
    // always follow left branch first
    if (obj.left) {
        traverse(obj.left);
    }

    // do stuff for leaf nodes
    if (obj.pitch) {
        console.log(obj.pitch);
    }

    // then the right branch if it exists
    if (obj.right) {
        traverse(obj.right);
    }
}

http://jsfiddle.net/alnitak/E2ZEB/

或更笼统地说:

function traverse(obj, func) {
    if (!obj) return;

    traverse(obj.left, func);
    func(obj);
    traverse(obj.right, func);
}
于 2013-05-07T15:47:41.810 回答
1

这是 Alnitak 答案的副本,但使用访问者模式进行了抽象。

function traverse(obj, cb) {
    cb(obj);
    if (obj.left) {
        traverse(obj.left, cb);
    }
    if (obj.right) {
        traverse(obj.right, cb);
    }
}

var melody2_mus = 
    { tag: 'seq',
      left: 
       { tag: 'seq',
         left: { tag: 'note', pitch: 'a4', dur: 250 },
         right: { tag: 'note', pitch: 'b4', dur: 250 } },
      right:
       { tag: 'seq',
         left: { tag: 'note', pitch: 'c4', dur: 500 },
         right: { tag: 'note', pitch: 'd4', dur: 500 } } }

traverse(melody2_mus, function(node) {
    if (node.pitch) {
        console.log(node.pitch);
    }
});

http://jsfiddle.net/E2ZEB/3/

于 2013-05-07T16:42:37.607 回答