面试时脑子短路了,特此来总结一番
image.png

数组方法

  1. forEach:遍历原数组,对每一项运行传入的函数,返回值为undefined

红宝书里说它不会修改原数组,但是我觉得应该视情况而定,比如下面这样修改了:

  1. const arr = [[1,2,3], [4,5,6], [7,8,9]]
  2. arr.forEach((item , idx, arr) => {
  3. arr[idx] = item.map(x => x + 1)
  4. })
  5. console.log(arr) // [[2, 3, 4], [5, 6, 7], [8, 9, 10]]
  1. map:不影响原数组,返回由每次调用函数返回值组成的新数组 ```javascript const arr = [[1,2,3], [4,5,6], [7,8,9]]

const res = arr.map((sub , idx) => { return ‘’ }) console.log(res) // [“”, “”, “”]

  1. 3. splice:对原数组进行增删改
  2. start: 开始索引,负数如`-n`代表length - n位置,如果`length - n < 0`那么就是第一项<br />deleteCount: 删除个数, 0或负数不删除<br />item1,item2,...: 插入元素
  3. ```javascript
  4. Array.prototyp.splice(start , deleteCount){
  5. if(start < 0) return this.length - start >= 0 ? this.length - start : 0
  6. if(deleteCount <= 0) deleteCount = 0
  7. }
  1. forEach和map一起用 ```javascript const arr = [[1,2,3], [4,5,6], [7,8,9]]

arr.forEach((sub, idx) => { // sub只是子数组引用 arr[idx] = sub.map(x => x+1) })

console.log(arr) // [[2, 3, 4], [5, 6, 7], [8, 9, 10]]

const arr = [[1,2,3], [4,5,6], [7,8,9]]

arr.forEach((sub, idx) => { const temp = sub.map(x => x+1) sub.splice(0,sub.length) sub.push(…temp) })

console.log(arr) // [[2, 3, 4], [5, 6, 7], [8, 9, 10]] ```

字符串方法

  1. indexOf