JS数组问题集合

119 阅读2分钟

1. 可以改变原数组的方法

  • splice

    • 添加或者删除数组的元素
        arr.splice(index,howmany,item1,...itemx)
      
  • sort

    • 排序
           //默认按照 ASCII 码值
           arr.sort()
      
           //升序
           arr.sort((a,b)=>a-b)
           
           //降序
           arr.sort((a,b)=>b-a)
      
  • pop

    • 删除数组最后一个值
  • shift

    • 删除数组第一个值
  • push

    • 往数组末尾添加一个元素
  • unshift

    • 往数组开头添加一个元素
  • reverse

    • 反转数组
  • copyWithin

    • ES6新增

    • 从数组的指定位置拷贝元素到数组的另一个指定位置中

      语法: array.copyWithin(target, start, end)
      参数:
           target  必需。复制到指定目标索引位置。
           start   可选。元素复制的起始位置。
           end 可选。停止复制的索引位置 (默认为 array.length)。如果为负值,表示倒数
    
    
  • fill

    • ES6新增,填充数组
    语法: array.fill(value, start, end)
    参数:
          value 必需。填充的值。
          start 可选。开始填充位置。
          end 可选。停止填充位置 (默认为 array.length)
          填充是从 start 位置开始,到 end-1 位置结束,不包含end位置
    

2. 判断是否是数组

  • instanceof

      [] instanceof Array //true
    
  • isArray

      Array.isArray([]) //true
    
  • constructor

      [].constructor === Array  //true
    
  • toString()

    在Object对象中有一个toString(),可以返回一个形如 "[object xxx]"的字符串。

      Object.prototype.toString.call([])  //[object Array]
    

3. 类数组

3.1 什么是伪数组

满足两个条件的对象就是类数组。

  • 有length属性,最好加上push方法
  • 属性要为索引属性
    • 常见的有函数参数的 arguments对象等
  {
      "0": 1,
      "2": 23,
      length: 2
  }

类数组并不能直接使用数组的方法,需要用call()或者apply()调用数组的方法。

类似于这样

  let arrObj = {
      0: 0,
      1: 1,
      2: 2,
      length: 3
  }
  let res = Array.prototype.slice.call(arrObj,0)
  console.log(res);

3.2 伪数组转变成真数组

  1. from()
  2. 自定义方法
  3. slice
  4. 扩展运算符
  • Array.from()

      let arrObj = {
          0: 0,
          1: 1,
          2: 2,
          length: 3
      }
      // 1. Array.form
      Array.from(arrObj)  //[0,1,2]
    
  • 自定义方法

     let arrObj = {
          0: 0,
          1: 1,
          2: 2,
          length: 3
      }
      let arr = []
      for(let i=0;i<arrObj.length;i++){
          arr.push(arrObj[i])
      }
      console.log(arr);
    
  • Array.prototype.slice.call(obj,0)

    • 截取函数
      let arrObj = {
          0: 0,
          1: 1,
          2: 2,
          length: 3
      }
      let res = Array.prototype.slice.call(arrObj,0)
      console.log(res);
    
  • 扩展运算符 ...

       function test(){
            console.log(arguments);
             console.log([...arguments]);  //[1,2,4,6]
      }
      test(1,2,4,6)