调用此函数时,我希望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);