对于一个向量,里面的元素可能是一个向量或数值,要求将其展开为一维向量;
非递归解法,思路非常简单:
a=[[3,4,5],[5,6,[8,9]]];
function spreadArr(arr){//展开平面向量
//思路:使用arr本身的shift()和concat()方法,如果队首为数值则push到新数组中,如果不是则concat到队尾
temp=[];
while(arr.length>0){
first=arr.shift() //取队首
// console.log(first);
if(typeof first=="number"){
temp.push(first);
}else{
arr=arr.concat(first);
}
}
return temp;
}
res=spreadArr(a);
console.log(res);