javaScript基础:统计数组/字符串等变量中各元素出现的次数

82 阅读1分钟

字符串可以通过三种方法转成数组,再进行元素统计
转数组的方法

  const a = 'sdfsadfe'
  // 第一种 split分隔符拆分
  console.log(a.split(''));
  // 第二种用...扩展运算符
  [..."abasdasd"]
  // 第三种Array构造函数from方法
  console.log(Array.from(a));

数组用reduce方法
reduce()  方法对数组中的每个元素按序执行一个由您提供的 reducer 函数,每一行 reducer 会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。
第一次执行回调函数时,不存在“上一次的计算结果”。如果需要回调函数从数组索引为 0 的元素开始执行,则需要传递初始值。

<script>
  const arr = ["1", "2", "1", "2", "3", "1", "1", "4", "3"]
  // 方法1
  const obj = arr.reduce((accumulator, currentValue) => {
    if (currentValue in accumulator) {
      accumulator[currentValue]++
    } else {
      accumulator[currentValue] = 1
    }
    return accumulator
  }, {})
  // 第二个参数为初始值,输出为一个对象,所以初始值设置为空对象
  console.log(obj)
</script>

控制台打印结果

image.png

遍历方法foreach map for-of filter等都可实现。for-of也可直接迭代tring的变量,进行计数
举个例子foreach

  // 方法2遍历数组需要定义一个空对象
  const obj = {}
  arr.forEach(item => {
    if (obj[item]) {
      obj[item]++
    } else {
      obj[item] = 1
    }
  })
  console.log(obj)

for-of (数组)

<script>
  const arr = ["1", "2", "1", "2", "3", "1", "1", "4", "3"]
  const a = {}
  for (const num of arr) {
    a[num] = a[num] ? a[num] + 1 : 1
  }
  console.log(a)
</script>

fo-of(字符串)

<script>
  const arr = '123124124'
  const a = {}
  for (const num of arr) {
    a[num] = a[num] ? a[num] + 1 : 1
  }
  console.log(a)
</script>

image.png