1.指定范围生成随机数
function random(min, max) {
if (arguments.length === 2) {
return Math.floor(min + Math.random() * ((max + 1) - min))
} else {
return null;
}
}
console.log(random(10,20));
2.去重
function unique(arr){
if (Array.hasOwnProperty('from')) {
return Array.from(new Set(arr));
} else {
var n = {}, r = [];
for (var i = 0; i < arr.length; i++) {
if (!n[arr[i]]) {
n[arr[i]] = true;
r.push(arr[i]);
}
}
return r;
}
}
var arr = [1,2,3,1,2,3,4];
console.log(unique(arr));
3.获取最大值
function max(arr) { return Math.max.apply(null,arr1) } var arr = [1,2,3,4,1,2,3,4]; console.log(max(arr));
4.获取最小值
function min(arr) {
return Math.min.apply(null,arr1)
}
var arr = [1,2,3,4,1,2,3,4];
console.log(min(arr));
5.判断一个元素中是否在数组中
function contains(arr,val) { return arr.indexOf(val) != -1 ? true : false; } var arr = [1,2,3,1,2,3,4]; console.log(contains(arr,1));
6.两个数组合并
var list1 = [1,2,3,4,5]; var list2 = [7,8,9,0]; function union () { var newArr = list1.concat(list2); return newArr; } console.log(union());
(更新中...)