const str = 'asafddasafawerfdasgdafgdada'
let total = {}
for (let i = 0; i < str.length; i++) {
if (total[str[i]]) {
total[str[i]].count += 1
} else {
total[str[i]] = {
count: 1,
position: []
}
}
let index = str.indexOf(str[i], i)
total[str[i]].position.push(index)
}
let max = 0
let key = ''
for (const k in total) {
if (max < total[k].count) {
max = total[k].count
key = k
}
}
console.log(total)
console.log(`${key}出现了${max}次,次数最多`) // a出现了9次,次数最多
console.log(key + '出现的位置索引为: ' + total[key].position.join(',')) // a出现的位置索引为: 0,2,6,8,10,16,20,24,26
for (const k in total) {
if (k === 'a') continue
const { count, position } = total[k]
console.log(`${k}出现了${count}次,出现的位置索引为: ${position.join(',')}`)
}
js统计字符出现的位置和次数
最新推荐文章于 2024-10-15 09:57:04 发布