需求:有一个字符串数组,找出出现次数最多的字符串及对应的数次。
1.代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let arr = ['a', 'b', 'a', 'c', 'd', 'g', 'g', 'g', 'h', 'j', 'j', 'k', 'k', '1', '2'];
const obj = {}
for (let i = 0; i < arr.length; i++) {
let s = arr[i]
if (obj[s] == undefined) {
obj[s] = 1
} else {
obj[s]++
}
}
let maxValue = -Infinity;
let maxProperty = ''
for (let property in obj) {
if (obj.hasOwnProperty(property)) {
if (obj[property] > maxValue) {
maxValue = obj[property]
maxProperty = property
}
}
}
console.log('出现次数最多的字符串:', maxProperty);
console.log('出现的数次:', maxValue);
</script>
</body>
</html>
2.解题步骤:
- 先定义一个空对象,然后遍历该数组,将每一项保存起来,作为对象的属性,判断是否有属性值,如果没有,则对应属性值+1;
- 否则遇到重复的属性,则属性值++。然后拿到的是去重后的属性和属性值,最后遍历处理后的对象。
- 定义两个中间值,属性为:maxProperty,属性值为:maxValue=负无穷大,通过for in 遍历该对象,判断属性是否对象自身的属性,而不是继承得到的属性。
- 判断属性对应的值是否大于maxValue,是,则将最大的值重新赋值给maxValue,属性值赋给maxProperty.最后可以拿到字符串出现最多的字符串和数次。