0%
数组转字符串(不改变原数组)
数组重排序(改变)
1 2
| Array.reverse() Array.sort()
|
- Array.sort()接收一个函数作为参数,函数传入两个参数value,
value1 < value2
返回一个负数,value1在value2之前;value1 > value2
返回一个正数,value1在value2之后;value1 === value2
返回一个0。1 2 3 4 5 6 7 8 9 10 11 12 13 14
| function compare(value1, value2){ if(value1 < value2) return -1 else if(value1 > value2) return 1 else return 0 }
function compare(value1, value2){ value1 - value2 ? -1 : 1 value1 - value2 ? 1 : -1 }
|
- Array.sort()原理:
1 2 3 4 5 6 7 8 9
| for(let i=0; i<length; i++){ for(let j=i+1; j<length; j++){ if(fn(i, j) > 0){ let temp = j; j = i; i = temp; } } }
|
查找元素位置(不改变)
1 2
| Array.indexOf(item, index) Array.lastIndexOf(item, index)
|
- item:查找元素,index:查找的起点位置,找不到返回-1
- 数组有两个相等元素,查找到第一个符合元素则返回位置,不会继续查找下去
查找是否包含某个元素(不改变)
1 2 3 4 5 6 7 8
| Array.findIndex(function(item, index, array){})
let color = ['r', 'b', 'g', 'r'] console.log(color.findIndex((item, index, array) => { return item === 'r' }))
Array.includes(item)
|
操作方法
- 两个数组连接(不改变)
- Array.slice(startIndex, endIndex),截取返回新数组 (不改变)
1 2 3 4 5
| let color = ['r', 'b', 'g', 'y', 'p'] console.log(color.slice(3, 4))
console.log(color.slice(-2, -1))
|
- Array.splice (改变)
- 删除:2个参数,要删除的第一项位置和要删除的项数,返回被删除的元素数组
- 插入:3个参数,起始位置、要删除项数、要插入的任意数量项
- 替换:3个参数,起始位置、要删除项数、要插入的任意数量项
- 如果没有被删除的项,则返回一个空数组
1 2 3 4 5 6 7 8 9
| let color = ['r', 'b', 'g'] console.log(color.splice(0, 1)) console.log(color)
console.log(color.splice(1, 0, 'y', 'o')) console.log(color)
console.log(color.splice(1, 1, 'r', 'p')) console.log(color)
|
栈方法(改变)
1 2
| Array.push() Array.pop()
|
队列方法(改变)
1 2
| Array.shift() Array.unshift()
|
迭代方法(不改变)
1 2 3 4 5
| Array.map(function(item, index, array){}) Array.forEach(function(item, index, array){}) Array.every(function(item, index, array){}) Array.some(function(item, index, array){}) Array.filter(function(item, index, array){})
|
Array.reduce & Array.reduceRight
- 迭代数组所有项,构建返回一个最终值
- 2个参数:一个function(prev, cur, index, array);一个起始值。
- 函数第一第二参数:第一次迭代发生在数组的第二项上,因此第一个参数是数组的第一项,第二个参数是数组的第二项
- 用法:
- 计算数组中每个元素出现的次数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| let color = ['r', 'b', 'g', 'r'] let res = color.reduce(function(prev, cur, index, array){ console.log(prev, cur) if(cur in prev) prev[cur]++ else prev[cur] = 1 return prev }, {}) console.log(res)
|
- 数组求和
- 数组去重
1 2 3 4 5 6 7 8 9 10
| let color = ['r', 'b', 'g', 'r'] let res = color.reduce(function(prev, cur, index, array){ console.log(prev, cur) if(prev.includes(cur)) return prev else prev.push(cur) return prev }, []) console.log(res)
|
- 多维数组转一维
1 2 3 4 5 6 7
| let color = ['r', [['b', 'g'], 'r']] let transform = function(val){ return val.reduce(function(prev, cur, index, array){ return prev.concat(Array.isArray(cur)? transform(cur) : cur) }, []) } console.log(transform(color))
|