需求:有一个字符串数组,找出出现次数最多的字符串及对应的数次。
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.最后可以拿到字符串出现最多的字符串和数次。
3.封装思想
我的想法是将这个解决方法封装起来,方便复用。
//封装方法.js
export function getMoreAndDoWeight(arr) {
const obj = {}
for (let i = 0; i < arr.length; i++) {
let s = arr[i]
if (obj[s] == undefined) {
obj[s] = 1
} else {
obj[s]++
}
}
return function () {
let maxValue = -Infinity;
let maxProperty = ''
for (let property in obj) {
if (obj.hasOwnProperty(property)) {//判断属性是否对象自身的属性,而不是继承得到的属性。
if (obj[property] > maxValue) {
maxValue = obj[property]
maxProperty = property
}
}
}
return { maxProperty, maxValue }
}
}
在封装方法.js文件中通过export导出方法。
然后通过ES6的语法在script中加入type=‘module’,在a.html文件中导入,
a.html
<!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 type="module">
import { getMoreAndDoWeight } from './封装方法.js'
let arr = ['a', 'b', 'a', 's', 'f', 'g', 'g', 'g', 'h', 'j', 'j', 'k', 'k', 'g', 'f', 'd', 'd', 's', 's', 's', 's', 's', 's', '3', '4', '4', '4', '3', '4', '3']
let moreData = getMoreAndDoWeight(arr)()
console.log('出现次数最多的字符串:', moreData.maxProperty);
console.log('出现的数次:', moreData.maxValue);
</script>
</body>
</html>