**
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 Math.random() - 0.5;
})
// [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