Javascript范围和递归

时间:2014-02-03 00:11:38

标签: javascript recursion scope

调用此函数时,我希望myStrings['A','B','C','D','E','F','G'],而实际上我正在看['A', 'B', 'G']。当递归调用a[i]等于[['C','D'],'E','F']时,函数会收到整个myArray。有什么想法吗?

var myArray = ['A','B',[['C','D'],'E','F'],'G'];

var myStrings = [];

function extractStrings(a) {

    for(var i=0; i<a.length; i++) {

        if(typeof a[i] === 'string') {
            myStrings.push(a[i]);
        } else if (typeof a[i] === 'object') {
            extractStrings[a[i]];
        }
    }
}

extractStrings(myArray);
console.log(myStrings);

1 个答案:

答案 0 :(得分:4)

这是一个简单的错字:

extractStrings[a[i]];

应该是:

extractStrings(a[i]);

Demonstration