高阳的技术专栏 gy

数组的高级用法

2018-07-15
gaoyang

阅读:

js

数组的高级用法

将一维数组 遍历成二维数组

   categorysArr () {
          const {categorys} = this
          const arr = []
          let smallArr = []
          categorys.forEach(c => {
            // 将全新的小数组保存到大数组中
            if(smallArr.length===0) {
              arr.push(smallArr)
            }

            // 将当前分类保存到小数组
            smallArr.push(c)

            // 如果刚好满了, 为后面创建一个新的小数组
            if(smallArr.length===8) {
              smallArr = []
            }
          })
          return arr
        }
      }

reduce()

    const arr = [1,4,6,8,9]
    const son = arr.reduce((prev,c)=> prev+c,0)
    console.log(son)

1.有return

2.返回最后统计的结果

findIndex()

      const arr = [1,4,6,8,9]
        const subscript = arr.findIndex(c => c === 6)
        console.log(subscript)  //28

1.有return

2.返回匹配数组元素下标

find()

      const arr = [1,4,{a:'tangsan',b:'wangyu'},{a:'join',b:'sany'},9]
         const obj = arr.find(c => c.a === 'tangsan')
         console.log(obj)  //{a: "tangsan", b: "wangyu"}

1.有return

2.返回匹配数组元素

map()

     var arr = [1, 2, 3, 4, 5];
     var arr2 = arr.map(function(item){
     return item*item;
     });
     console.log(arr2); //[1, 4, 9, 16, 25]

1.有return

2.遍历这个数组返回一个新数组

filter()

     var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
     var arr2 = arr.filter(function(x, index) {
     return index % 3 === 0 || x >= 8;
     });
     console.log(arr2); //[1, 4, 7, 8, 9, 10]

1.有return

2.返回过滤之后的新数组

伪数组

定义:

1、拥有length属性,其它属性(索引)为非负整数(对象中的索引会被当做字符串来处理,这里你可以当做是个非负整数串来理解)

2、不具有数组所具有的方法

  //这就是伪数组
   var arr = {
       length: 3,
       "0": "first",
       "1": "second",
       "2": "third"
   };

Array.from(arr)

将伪数组转换成真数组

   var arr = {
        length: 3,
        "0": "first",
        "1": "second",
        "2": "third"
      };
      const newArr = Array.from(arr)
      console.log(newArr)   //["first", "second", "third"]

forEach()

   let arr=[2,3,4]
   			arr.forEach((item,index)=>{
   				arr[index]++
   			})
   			console.log(arr)

上一篇 js

下一篇 vue笔记

Comments

Content