1.获取字符出现的次数
let str = 'aaaauedawwwwa'
function getStr(str) {
let o = {}
for(let i = 0; i < str.length; i++) {
let key = str.charAt(i)
if (o[key]) {
o[key] ++
} else {
o[key] = 1
}
}
return o
}
console.log(getStr(str)) // {a: 6, u: 1, e: 1, d: 1, w: 4}
2. 数组降维并且去重和排序
let array = [1,2,4,[10, 20,26,[10,15,80]],[11,12],1,1,1,2,2,10,15,11,11]
function flatArray(array) {
let result = []
array.forEach(item => { // 降维
if (Array.isArray(item)) {
result = result.concat(arguments.callee(item))
} else {
result.push(item)
}
});
let arr = []
result.forEach(item => { // 去重
if (!arr.includes(item)) {
arr.push(item)
}
})
return arr.sort((a, b) => { // 排序
return a - b
})
}
console.log(flatArray(array)) // [1, 2, 4, 10, 11, 12, 15, 20, 26, 80]
3. 数组排序
// 冒泡排序
let arr = [1,5,3,7,5,4,9,7,2]
function sortFn(arr) {
for(let i = 0; i < arr.length - 1; i++) {
for(let j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
let temp = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = temp
}
}
}
return arr
}
console.log(sortFn(arr)) // [1, 2, 3, 4, 5, 5, 7, 7, 9]
4. 大小写字符互相转换
let strCode = 'AaAbCZz'
function getSwitch (str) {
let arr =[]
for (let i = 0; i < str.length; i++) {
let t = str[i].charCodeAt() // 获取字符的Unicode码
if (t >= 65 && t <= 90) { // A-Z 65-90
// String.fromCharCode() 把字符串码转为字符串
// 大写字母比小写字母小32
t = String.fromCharCode(t + 32)
} else {
t = String.fromCharCode(t - 32)
}
arr.push(t)
}
return arr.join('')
}
console.log(getSwitch(strCode)) // aAaBczZ