让我纸上手写我确实写不出啊。。。。
挺无语的一题:
// "aabbbbaaacccdd" 按照 字母的出现次数从大到小排序,最终结果为['a','b','c','d']
let str = "bbbbaaddaaaccc" // -> ['a','b','c']
function getCount(){
let jsonObj = {} // {a:5,b:4,c:3}
for(let i in str){
if(jsonObj[str[i]] == undefined){
jsonObj[str[i]] = 1
}else{
jsonObj[str[i]] = jsonObj[str[i]] + 1
}
}
return jsonObj
}
function mySort(obj){
let arr = []
let countKeys = Object.keys(obj) // ['a','b','c','d']
for(let i = 0; i<countKeys.length-1;i++){
for(let j = 0;j<countKeys.length-1-i;j++){
if(obj[countKeys[j]] < obj[countKeys[j + 1]]){
let temp = countKeys[j];
countKeys[j] = countKeys[j+1]
countKeys[j+1] = temp
}
}
}
return countKeys
}
console.log(mySort(getCount()));
深克隆:
// 类型检查
function getType(obj){
return Object.prototype.toString.bind(obj)().slice(8,-1)
}
function deepClone(obj){
let result;
switch(getType(obj)){
case 'Object':{
result = {}
break;
}
case 'Array':{
result = []
break;
}
default:{
result = obj;
}
}
for(let key in obj){
if(result == 'Object' || result == 'Array'){
deepClone(obj[key])
}else{
result[key] = obj[key]
}
}
return result;
}
console.log(deepClone({name:123,arr:[1,2,3,4]}));
数组去重复:
let arr1 = [1,1,2,2,4,4,3,3]
let arr2 = []
function foo(arr1){
for(let i in arr1){
if(arr2.indexOf(arr1[i]) === -1){
arr2.push(arr1[i])
}
}
}
foo(arr1)
console.log(arr2);