数组方法总结

157 阅读2分钟

先创建一个数组如下:

     let nums = [1,2,3,4,5,6];
  1. concat方法:连接2个或更多数组,并返回结果。

       let res1 = nums.concat([7,8,9]);      
       console.log(res);         //数组变为1,2,3,4,5,6,7,8,9 可以传多个参数(数组),顺序按照参数的顺序
    
  2. every方法:对数组的每一项运行给定的函数(参数),当改函数对于数组的每一项的返回值都为true时返回true,否则返回false。

       let res2 = nums.every(
            function(b){
                return b>0
            }
       )
       console.log(res); //true 但是如果有一个是false则返回false
    
  3. filter方法:对数组中的每一项运行给定的函数(参数),返回该函数会返回true的项所组成的数组。

       let res3 = nums.filter(
            function(b){
                return b>4
            }
       )
       console.log(res); // 5,6
    
  4. forEach方法:没有返回值,对数组的每一项运行给定的函数。

       nums.forEach(
           function(b){
               console.log('haha')
           }
       )
        //打印六行haha
    
  5. join方法:将数组返回成字符串,默认元素之间用逗号分隔。

       let res4 = nums.join()
       console.log(res4); //1,2,3,4,5,6
       let res5 = nums.join('-')
       console.log(res5); //1-2-3-4-5-6
    
  6. indexOf方法:返回第一个与参数相同的数组元素的索引。

       let res6 = nums.indexOf(2)
       console.log(res6) // 1     如果数组内有相同的取索引值最小的那个
    
  7. lastIndexOf方法:返回最后一个与参数相同数组元素的索引。

       let res7 = nums.lastIndexOf(2)
       console.log(res7) // 1     如果数组内有相同的取索引值最大的那个
    
  8. map方法:对数组中的每一项运行给定的函数,将返回每次函数调用的结果组成的数组。(就像更新)

        console.log(a.map(
          function name() {
              return 1
          }
        )); //打印的是一个数组,数组的每一项都是1.
    
  9. reverse方法:倒序数组。

       console.log(a.reverse());//两级反转!6,5,4,3,2,1
    
  10. slice方法:接受两个参数,将数组里对应索引范围的元素作为新数组返回。

      console.log(a.slice(1,3));//第一个参数是开始(包含),第二个是结束(不包含),
      如果只传一个参数则从第参数索引位置开始(包含)到结束
    
  11. some方法:对数组的每一项运行给定函数,只要有一项为true就返回true。

      console.log(a.some(
         function name(){
             return true
         }
      ));// true
    
  12. sort方法:按照顺序排序,支持传入指定排序方法的函数作为参数。

  13. toString方法:将数组作为字符串返回。

  14. valueOf方法:和toString类似,将数组作为字符串返回。 下面这些数组方法会改变原数组 shift();   unshift();   push();   shift();   pop();   sort();   reverse();   splice();