2021-04-02

2021-04-02  本文已影响0人  小王子__

Js数组常用的方法

var a = [1, 2, 3]
var b = a.push(4)
console.log(a) // [1,2,3,4]
console.log(b) // 4
var a = [1, 2, 3]
var b = a.pop()
console.log(a) // [1,2]
console.log(b) // 3
var a = [1, 2, 3]
var b = a.unshift(0)
console.log(a) // [0,1,2,3]
console.log(b) // 4
var a = [1, 2, 3]
var b = a.shift()
console.log(a) // [2,3]
console.log(b) // 1

表示从index开始删除length个元素,并从index开始新增元素1~N,放回被删除的数组里

对数组进行删除修改,返回被删除的元素组成的数组,改变原数组

var a = [1, 2, 3, 4, 5, 6]
var b = a.splice(1, 3, 100, 200, 300)
console.log(a) // [1, 100, 200, 300, 5, 6]
console.log(b) // [2, 3, 4]

返回新数组,不改变原数组

var a = [1, 2, 3]
var b = a.slice(0, 2)
var c = a.slice()
console.log(a) // [1,2,3]
console.log(b) // [1,2]
console.log(c) // [1,2,3]
var a = [1, 2, 3, 4, 5, 6]
console.log(a.join('|')) // 1|2|3|4|5|6
console.log(a) // [1, 2, 3, 4, 5, 6]

返回新数组,不改变原数组

var a = [1, 2, 3]
var b = [4, 5, 6]
var c = a.concat(b)
console.log(a) // [1,2,3]
console.log(b) // [4,5,6]
console.log(c) // [1,2,3,4,5,6]
var a = ['a', 'b', 'd', 'c']
var b = a.sort()
console.log(a) // ['a', 'b', 'c', 'd']
console.log(b) // ['a', 'b', 'c', 'd']
var a = [1, 2, 3, 4, 5, 6]
var b = a.reverse()
console.log(a) // [6, 5, 4, 3, 2, 1]
console.log(b) // [6, 5, 4, 3, 2, 1]

lastIndexOf(某元素,startIndex)和indexOf相同,区别在于从尾部向首部查询

不改变原数组,返回找到的index,否则返回-1

若不使用下标,一般用includes代替indexOf

var str = 'JerryJerry'
console.log(str.indexOf('r')) // 2
console.log(str.lastIndexOf('J')) // 4
var a = [1, 2, 3, 4, 5, 6, 7, 8]
var b = a.filter((current, index, array) => {
  return current > 4
})
console.log(a) // [1, 2, 3, 4, 5, 6, 7, 8]
console.log(b) // [5, 6, 7, 8]
var a = [1, 2, 3, 4, 5, 6]
var b = a.map((current, index, array) => {
  return current + 1
})
console.log(a) // [1,2,3,4,5,6]
console.log(b) // [2,3,4,5,6,7]
var a = [2, 3, 4, 5, 6, 7, 8]
var b = a.every((cur, idx, ary) => {
  return cur > 1
})
var c = a.every((cur, idx, ary) => {
  return cur < 6
})
console.log(a) // [1,2,3,4,5,6,7,8]
console.log(b) // true
console.log(c) // false
var a = [1, 2, 3, 4, 5, 6]
var b = a.some((cur, idx, ary) => {
  return cur > 3
})
var c = a.some((cur, idx, ary) => {
  return cur < 1
})
console.log(a) // [1, 2, 3, 4, 5, 6]
console.log(b) // true
console.log(c) // false
var arr = [100, 200, 300, 400]
arr.forEach(e => console.log(e)) // 100 200 300 400
var arr = [100, 200, 300]
var str = arr.toString()
console.log(arr) // [100, 200, 300]
console.log(str) // 100, 200, 300

slice(start, end) start开始下标 => end结束下标(不含)

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var str = arr.slice(2, 5)
console.log(arr) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(str) // [3, 4, 5]
上一篇下一篇

猜你喜欢

热点阅读