1.把字符串翻转 “kjihgfedcba”
let str = "abcdefghijk";
console.log(str.split('').reverse().join(''));
2.分别统计出 及格和不及格的分数总和
let subjectList = [
{ score: 10 },
{ score: 20 },
{ score: 30 },
{ score: 40 },
{ score: 50 },
{ score: 60 },
{ score: 70 },
{ score: 80 },
{ score: 90 },
{ score: 100 },
];
// 及格的总分
const passSum = subjectList.filter(item=> item.score>59).reduce((acc,item)=> acc+=item.score ,0)
//不及格分数
const failSum = subjectList.filter(item=> item.score<60).reduce((acc,item)=> acc+=item.score ,0)
3. 截取域名
let href = "http://www.baidu.com?name=zs&age=18&sex=男";
console.log(href.split('?')[0]);//http://www.baidu.com
4 域名后参数转对象
获取问号后面的参数 name=zs&age=18&sex=男 并且转成对象 {name:‘zs’,age:18,sex:‘男’}
const paramsStr = href.split('?')[1] // name=zs&age=18&sex=男
const paramsArr = paramsStr.split('&') // ['name=zs', 'age=18', 'sex=男']
// 第一种写法
let obj = {}
paramsArr.forEach(it=>{
// console.log(it.split('=')[0],it.split('=')[1]);
obj[it.split('=')[0]]=it.split('=')[1]
})
// 第二种
// const res = href.split('?')[1].split('&').reduce((acc,it)=> {
// console.log(it);
// acc[it.split('=')[0]] = it.split('=')[1]
// return acc
// },{})
5 数组元素去重
let arr = [1, 2, 3, 4, 5, 1, 2, 3];
// 5. 数字去重
// 第一种写法
// let newArr = []
// arr.forEach(it=>{
// // includes(ture/false) find(值) findIndex(索引/-1)
// if(!newArr.includes(it)){
// newArr.push(it)
// }
// })
//第二种
const newArr = arr.reduce((acc,item)=> acc.includes(item)? acc : [...acc,item] ,[])
console.log(newArr,'newArr');
6 统计数组中每个元素出现的次数
统计数组中每个元素出现的次数 {1:2,2:2,3:2,4:1,5:1}
let obj1 = { }
arr.forEach(it =>{
// if(obj1[it]) {
// obj1[it] ++
// }else {
// obj1[it] = 1
// }
obj1[it]? obj1[it] ++ : obj1[it] = 1
})