【JS】【基础】Array相关API

2021-08-25  本文已影响0人  今夜相思又几许

数组是一种类列表对象,它的原型中提供了遍历和修改元素的相关操作。JavaScript 数组的长度和元素类型都是非固定的。因为数组的长度可随时改变,并且其数据在内存中也可以不连续,所以 JavaScript 数组不一定是密集型的,这取决于它的使用方式。一般来说,数组的这些特性会给使用带来方便,但如果这些特性不适用于你的特定使用场景的话,可以考虑使用类型数组

1. Array.prototype.concat(array|value...)

2. Array.prototype.copyWithin(targetIndex, startIndex, endIndex)

{
  const list = [1, 2, 3, 4, 5, 6]
  console.log(list.copyWithin())
  console.log(list.copyWithin(0, 2)) // [3, 4, 5, 6, 5, 6]
  // 需求:把前两个挪动到最后
  const list2 = list.copyWithin(list.length - 2, 0, 2) // [3, 4, 5, 6, 3, 4]
  console.log(`原数组`, list)
  console.log(`挪动后数组`, list2)
}

3. Array.prototype.entries()

4. Array.prototype.every(v=>boolean)

5. Array.prototype.fill(value, startIndex, endIndex)

6. Array.prototype.filter()

7. Array.prototype.find()

8. Array.prototype.findIndex()

9. Array.prototype.flat()

  1. 递归 + for + concat
function flatten(list = []) {
  let result = []
  for (let i = 0; i < list.length; i++) {
    const item = list[i]
    if (Array.isArray(item)) {
      result = result.concat(flatten(item))
    } else {
      result.push(item)
    }
  }
  return result
}
  1. 递归 + for + push
function flatten(list = []) {
  let result = []
  for (let i = 0; i < list.length; i++) {
    const item = list[i]
    if (Array.isArray(item)) {
      result.push(...flatten(item))
    } else {
      result.push(item)
    }
  }
  return result
}
  1. while 循环遍历
function flatten(list = []) {
  while (list.some((v) => Array.isArray(v))) {
    list = [].concat(...list)
  }
  return list
}
  1. 递归 + reduce
function flatten(list = []) {
  return list.reduce((res, item) => {
    return res.concat(Array.isArray(item) ? flatten(item) : item)
  }, [])
}
  1. 中间变量暂存
function flatten(list = []) {
  const stack = [...list]
  const result = []
  while (stack.length) {
    const first = stack.shift()
    Array.isArray(first) ? stack.unshift(...first) : result.push(first)
  }
  return result
}

10. Array.prototype.flatMap()

11. Array.prototype.forEach()

12. Array.from()

{
  // 需求:获取html所有节点
  const elements = document.querySelectorAll('*')
  console.log(Array.isArray(elements)) // false 得到的并不是一个真的数组
  console.log(elements) //
  const elementsArray = Array.from(elements) // 将类数组转换为数组
  console.log(Array.isArray(elementsArray)) // true
  console.log(elementsArray)
}

13. Array.prototype.includes()

14. Array.prototype.indexOf()

15. Array.isArray()

16. Array.prototype.join()

17. Array.prototype.keys()

18. Array.prototype.values()

19. Array.prototype.lastIndexOf()

20. Array.prototype.map()

21. Array.of()

22. Array.prototype.pop()

23. Array.prototype.push()

24. Array.prototype.reduce()

25. Array.prototype.reverse()

26. Array.prototype.shift()

27. Array.prototype.slice()

28. Array.prototype.some()

29. Array.prototype.sort()

30. Array.prototype.splice()

31. Array.prototype.toString()

32. Array.prototype.unshift()

上一篇 下一篇

猜你喜欢

热点阅读