數組的打亂以及求對象數組中某個元素的最大最小值

**

1、數組的打亂

**
1)使用foreach遍歷,隨機數取下標,然後位置互換。

let a = [1,3,5,6,7,2,4,9,8,6];
a.forEach(function(item,index){
    let r = parseInt(Math.random()*a.length);
    [a[index],a[r]] = [a[r],a[index]]
})
//[5, 7, 1, 6, 8, 6, 9, 2, 3, 4]
//[6, 8, 2, 4, 9, 7, 5, 3, 6, 1]
//[6, 8, 4, 2, 5, 9, 6, 1, 7, 3]

2)使用sort排序,隨機數判斷是否進行排序。

let a = [1,3,5,6,7,2,4,9,8,6];
a.sort(function(x,y){
    return x>y ? (Math.random() > 0.5 ? 1 : -1) : (Math.random() > 0.5 ? -1 : 1);
})
// [4, 6, 8, 3, 5, 2, 1, 6, 7, 9]
// [1, 8, 5, 3, 7, 6, 6, 2, 4, 9]
// [3, 6, 6, 1, 2, 7, 4, 9, 5, 8]

**

2、求對象數組中某個元素的最大最小值

**
使用reduce,根據reduce逐項計算並返回之前項的特點,很輕鬆完成最大最小值的運算

a = [{
    value:10
},{
    value:20
},{
    value:5
},{
    value:100
}]
maxItem = a.reduce(function(x,y){
    return x.value > y.value ? x : y
});
maxItem.value;//100
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章