js数组字符串常用方法总结

不改变原数组的方法有: concat、join、slice、map

改变原数组的方法:splice、sort 、push、forEach

 1.删除数组中指定的元素  indexOf() & splice() 

    let index = array.indexOf(val)// 获取该元素在数组中的索引
    // 若数组中存在该元素
    if(index > -1){ 
        array.splice(index, 1)
    }

2.字符串去重 indexOf()

let str ='hheello'
let newStr = ''
for(let i = 0; i < str.length; i++){
   if(newStr.indexOf(str[i])==-1){
     newStr+=str[i]
   }
}

3.数组去重

  • Array.filter() + indexOf
  • for...of + includes()

4.数组复制

  • Object.assign() 
  • 扩展运算符
  • array.slice()
  • cocat()

5.向数组中添加元素/数组/合并数组

  • push
  • concat
  • splice
  • unshift(头部添加)
  • Array.prototype.push.apply()

6.数组排序

7.取数组最大值

  • Math.max.apply(null,arr)
  • Math.max(...arr)

8.数组铺平

  • flat(Infinity)展开任意嵌套的深层数组
  • push+concat 递归
  • reduce concat 递归
  • pop push
  • generator yield 递归

9.字符串转数组

10.数组转为字符串

  • array.join()

11.遍历数组

  • for...of(该方法可遍历字符串、数组)
  • forEach()
  • map()
  • some()
  • every()
  • filter()
  • reduce()

12.遍历字符串

  • for...of
发布了32 篇原创文章 · 获赞 1 · 访问量 2926

猜你喜欢

转载自blog.csdn.net/yyk5928/article/details/101049859