forEach遍历数组
let arr = [21, 3, 4, 43, 232, 45, 14, 13, 342]
// arr.forEach()遍历数组
// v -> value , i ->索引
arr.forEach(function(v, i) {
console.log(v, i);
})
需求:统计字符串 'abcoefoxyozzopp' 中每个字符出现的次数(字符串可以随意设置)
// 定义一个字符串
let str = 'abcoefoxyozzopp'
let str1 = 'gasgiaxjsydqhnuiyobj'
// 封装成函数
function getObj(str) {
// 分割字符串为数组
let arr = str.split('')
// 定义一个对象统计字符出现的次数
let obj = {}
//遍历数组
arr.forEach(function(v, i) {
// console.log(v, i);
// 判断obj{}里面是否有obj[v],有就加1,没有就赋值
if (obj[v]) {
obj[v] += 1
} else {
obj[v] = 1
}
})
return obj
}
let res = getObj(str1)
console.log(res);