JS 数组常用操作笔记

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34518793/article/details/89358679

1、随机生成一个数字组成的数组,并保证没有重复的项

let arr = [];
for(let i=0; i<9; i++){
    let num = parseInt(Math.random() * 10);
    let isRepeat = arr.some((item) => num == item);
    isRepeat ? console.log('重复了') : arr.push(num);
}

2、数组去重,返回一个新数组

let arr = [1,2,3,2,3,4,5];
let arrNew = [];
arr.forEach((item) => {
    let isRepeat = arrNew.some((itemNew) => itemNew == item);
    isRepeat ? console.log('重复了,跳过') : arrNew.push(item);
})
console.log(arrNew) // [1,2,3,4,5]

这里使用set(),同样可以达到目的,如上面的代码可以写成:let arrNew = new Set(arr),需要注意的是,set()是精确运算,1 和 '1' 会当成两个不一样的值。

3、查找最小(取最大值反着来就可以了)

let arr = [5,6,1,2,4,8];
let min = {
    value: arr[0],
    index: 0
}
arr.forEach((item, index) => {
    min = {
        value: item < min.value ? item : min.value,
        index: item < min.value ? index : min.index,
    }
})
console.log(min) // { value: 1, index: 2}

原文地址:http://blog.xuxiangbo.com/im-47.html

猜你喜欢

转载自blog.csdn.net/qq_34518793/article/details/89358679