数组方法
- forEach:遍历原数组,对每一项运行传入的函数,返回值为undefined
红宝书里说它不会修改原数组,但是我觉得应该视情况而定,比如下面这样修改了:
const arr = [[1,2,3], [4,5,6], [7,8,9]]
arr.forEach((item , idx, arr) => {
arr[idx] = item.map(x => x + 1)
})
console.log(arr) // [[2, 3, 4], [5, 6, 7], [8, 9, 10]]
- map:不影响原数组,返回由每次调用函数返回值组成的新数组 ```javascript const arr = [[1,2,3], [4,5,6], [7,8,9]]
const res = arr.map((sub , idx) => { return ‘’ }) console.log(res) // [“”, “”, “”]
3. splice:对原数组进行增删改
start: 开始索引,负数如`-n`代表length - n位置,如果`length - n < 0`那么就是第一项<br />deleteCount: 删除个数, 0或负数不删除<br />item1,item2,...: 插入元素
```javascript
Array.prototyp.splice(start , deleteCount){
if(start < 0) return this.length - start >= 0 ? this.length - start : 0
if(deleteCount <= 0) deleteCount = 0
}
- 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]] ```
字符串方法
查
- indexOf