1.实现一个方法,把传入的多维数组变成以一维素组
比如[1,[2],[3,[4]], [5,[6,[7]]]] 变成 [1,2,3,4,5,6,7]
// 跟深拷贝一样 考察函数的递归调用
let arr = [1,[2,[3,[4,[5]]]]]
let newArr = []
function mulToOneArr(arr){
for(let i = 0;i<arr.length;i++){
if(arr[i] instanceof Array){
mulToOneArr(arr[i])
} else {
newArr.push(arr[i])
}
}
return newArr
}
let newArr1 = mulToOneArr(arr)
console.log(newArr1)
2."lkasuohwhlasihilsbnbalsswejbcasl" 找出重复的字母及个数
let str = 'lkasuohwhlasihilsbnbalsswejbcasl'
// let str = 'aabbcccd'
function numStr(str){
let oldArr = str.split('')
let newArr = []
let obj = {}
for(let i=0;i<oldArr.length;i++){
console.log(oldArr[i])
if(newArr.indexOf(oldArr[i]) > -1){
obj[oldArr[i]]++
} else {
newArr.push(oldArr[i])
obj[oldArr[i]] = 1
}
}
return obj
}
let num = numStr(str)
console.log(num)
3.写一个方法,把如下数组按从小到大排序,接受name参数,按name排序;接受age参数,按age排序;
[{name: 'tom',age: 32},{name: 'white',age: 28},{name: 'jack',age: 12},{name: 'terry',age: 41}]
function sortArr(arr = [], key = 'age'){
for(let m = 0;m < arr.length/2;m++){
for(let i = 0; i < arr.length - 1; i++){
if(arr[i][key] > arr[i+1][key]){
[arr[i],arr[i+1]] = [arr[i+1],arr[i]]
}
}
}
return arr
}
// let arr = [{name: 'a',age: 32},{name: 'b',age: 28},{name: 'c',age: 12},{name: 'd',age: 41}]
let sort = sortArr(arr,'age')
console.log(sort)
网友评论