打印数组中元素出现的次数(字符串索引)

83 阅读1分钟
    const stringtype: { [type: string]: number } = {} //定义字符串索引类型
    const arr = [1, 4, 6, 6, 4, 2, 1, 3, 1]
    arr.forEach(x => {
        if (
            Object.keys(stringtype).filter(y => y == x.toString()).length <
            1
        ) {
            stringtype[x.toString()] = 1
            return
        }
        stringtype[x.toString()]++
    })
    for (const i in stringtype) {
        //打印值
        console.log(i + "出现的次数是:" + stringtype[i])
    }
    

image.png