zhh10 / Notes

前端中react、Vue、ES6、css3、webpack、模块化等思维导图
12 stars 1 forks source link

数组技巧 #17

Open zhh10 opened 4 years ago

zhh10 commented 4 years ago

使用splice

for(var i = 0;i<arr.length;i++){
     for(var j = i+1;j<arr.length;j++){
          arr.splice(j,1);
          j-- 
  }
}

循环迭代

var arr = [1,1,2,3,4,5,6,6,9,8,9];
    var p =[];
    for(var i = 0;i<arr.length;i++){
        if(p.indexOf(arr[i]) == -1){
            p.push(arr[i])
        }
    }

使用es6 Set去重

function unique (arr) {
  return Array.from(new Set(arr))
}

使用filter

var arr = [1,2,3,4,4,5,6,6,6] 
var arr2 = arr.filter((item,index)=>{
    return !arr.slice(0,index).includes(item)
})

使用对象去重

let obj = {};
for(let i = 0;i<arr.length;i++){
    let item = arr[i]
    if(obj[item]){
        arr[i] = arr[arr.length - 1];
        arr.length--;
        i--;
        continute;
    }
    obj[item] = item;
}
zhh10 commented 4 years ago

生成类似[1-100]这样的数组

let arr = new Array(100).fill(0).map((item,index) => index + 1)

数组取交集

let a = [1,2,3]
let b = [3,4,5]
let c = [...new Set(a)].filter(item => b.includes(item))

数组取差集

let a = [1,2,3]
let b = [3,4,5]
let c = [...new Set([...a,...b])].filter(item => !a.includes(item) || !b.includes(item))

数组转对象

let arr = [1,2,3]
let obj = {...arr}

检测数组所有元素是否都符合判断条件

let arr = [1,2,3,4,5]
arr.every(item => typeof item === 'number')

检测数组是否有元素符合判断条件

let arr = [1,2,3,4,5] 
arr.some(item => typeof item === 'number')

找到第一个符合条件的元素/下标

let arr = [1,2,3,4,5] 
let findItem = arr.find(item => item === 3)
// 找到子项
let findIndex = arr.findIndex(item => item === 3)
// 找到子项对应的下标