描述
统计字符串中每个字符的出现频率,返回一个 Object,key 为统计字符,value 为出现频率
- 不限制 key 的顺序
- 输入的字符串参数不会为空
- 忽略空白字符
实现
function count(str) {
if(str.length>0){
let arr=str.split('')//将字符串转换为数组
console.log(arr)
//遍历数组,删除空字符串的数组
for(let index in arr){
// console.log(index)
if(arr[index]==' '){
arr.splice(index,1)
}
}
let obj={}
for(let item of arr){
if(obj.hasOwnProperty([item])){
obj[item]++
// console.log(obj)
}else{
obj[item]=1
// console.log(obj)
}
}
return obj
}
}
let str='hello world'
console.log(count(str))
注意点
- 判断一个对象中是否存在某个属性
obj.hasOwnProperty([item])
- 将字符串转换为数组
str.split('')
- 遍历数组
for(let index in arr)
// index为下标
for(let item of arr)
// item为数值
- 删除数组中某个指定的元素
arr.splice(index,1)
//index指开始下标,1表示删除的个数