js常用方法集合

导语:今天来说一下js中经常用到的去重,排序等方法。

# 求多维数组的和

var total = 0; //初始值
function getArrSum(arr) {
    if ((arr instanceof Array) || (arr && typeof arr == 'object' && 'length' in arr)) {
        for (let i = 0; i < arr.length; i++) {
            if (!arr[i]) {
                continue;
            }
            if (typeof arr[i] == 'number') {
                total += arr[i];
            }else if ((arr[i] instanceof Array)  || (arr[i] && typeof arr[i] == 'object' && 'length' in arr[i])) {
                getArrSum(arr[i]);
            }
        }
    } else {
        throw new Error('getArrSum():arr must be array!');
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

实例:

var arr = [1,[123],[45,[6,7,8]]];
getArrSum(arr);
console.log(total); //result is 190
1
2
3

# 返回参数中的最大值

function max() {
  var m = Number.NEGATIVE_INFINITY;
  for (let i = 0; i < arguments.length; i++) {
    const element = arguments[i];
    if (element > m) {
      m = arguments[i];
    }
  }
  return m;
}
1
2
3
4
5
6
7
8
9
10

实例:

var large = max(10,20,1111,1212);
console.log(large); // result is 1212;
1
2

# 检测参数类型求和

// 参数类型
function getSum(a) {
    if ((a instanceof Array) || (a && typeof a == 'Object' && 'length' in a)) {
        var total = 0;
        for (let i = 0; i < a.length; i++) {
            let element = a[i];
            if (!element) { continue; }
            if (typeof element == 'number') {
                total += element;
            } else {
                throw new Error("sum():all array elements must be an number!");
            }
        }
        return total;
    } else {
        throw new Error("sum():argument must be an array!");
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

实例:

var res1 = getSum([123,12,15,21,54]);
var res2 = getSum(121);
var res3 = getSum([12,31,'121']);
console.log(res1); // result is 225;
console.log(res2); // result is Uncaught Error: sum():argument must be an array!;
console.log(res3); // result is Uncaught Error: sum():all array elements must be an number!
1
2
3
4
5
6

# 返回阶乘

// 返回阶乘
var stratum = function (num) {
    if (num <= 1) {
        return 1;
    }
    return num*arguments.callee(num-1);
}
1
2
3
4
5
6
7

实例:

console.log(stratum(5)); // result is 120
1

# 数组排序

//数组元素为数字的排序(升序)
function sortArrayUp(a,b) {
    return b - a;
}

//数组元素为数字排序(升序)
function sortArrayDown(a,b) {
    return a - b;
}

//数组元素为对象排序
function sortObject(protoname,type) {
    // 如果type是up,是升序,否则为降序
    return function (a,b) {
        if (type == 'up') {
            return b[protoname] - a[protoname];
        } else {
            return a[protoname] - b[protoname];
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

实例:

var arr = [12,13,234,121,1212,334,212,520,125];
var resa = arr.sort(sortArrayUp);
var resb = arr.sort(sortArrayDown);
console.log(resa); //result is [1212, 520, 334, 234, 212, 125, 121, 13, 12];
console.log(resb); //result is [12, 13, 121, 125, 212, 234, 334, 520, 1212];

var arrb = [
    {num: 12,name: 'orange'},
    {num: 112,name: 'banana'},
    {num: 42,name: 'apple'},
    {num: 31,name: 'orange'}
]
var resc = arrb.sort(sortObject('num','up'));
var resd = arrb.sort(sortObject('num','down'));
console.log(resc);
/* result is
{num: 112,name: 'banana'},
{num: 42,name: 'apple'},
{num: 31,name: 'orange'},
{num: 12,name: 'orange'}
*/
console.log(resd);
/* result is
{num: 12,name: 'orange'},
{num: 31,name: 'orange'},
{num: 42,name: 'apple'},
{num: 112,name: 'banana'}
*/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

# 数组去重

// 数组去重
function arrayRemoveRepeat(arr,type,name) {
    var arr = arr; //数组
    var type = type; //类型,数组元素为对象,传'object',否则传'number'
    var name = name || ''; // 数组元素为对象,是对象的属性判断值;
    if ((arr instanceof Array) || (typeof arr == 'Object' && 'length' in arr)) {
        var newArr = [];
        var len = arr.length;
        for (let i = 0; i < len; i++) {
            if (!arr[i]) { continue; }
            if (type == 'object') {
                if (typeof arr[i] == 'object') {
                    if (newArr.indexOf(arr[i][name]) == -1) {
                        newArr.push(arr[i][name]);
                    }
                } else {
                    throw new Error("arrayRemoveRepeat():all element must be an object!");
                }
            } else if (type == 'number') {
                if (typeof arr[i] == 'number') {
                    if (newArr.indexOf(arr[i]) == -1) {
                        newArr.push(arr[i]);
                    }
                } else {
                    throw new Error("arrayRemoveRepeat():all element must be an number!");
                }
            }
        }
        return newArr;
    } else {
        throw new Error("arrayRemoveRepeat():argument must be an array!");
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

实例:

// 对象情况下:
var arr31 = [{num: 12},{num: 12},{num: 1},{num: 13},{num: 13},{num: 13}];
var arr32 = arrayRemoveRepeat(arr31,'object','num');
console.log(arr32); // result is [12, 1, 13];

// 数字情况下:
var arr22 = [12,12,11,212,1243,2321,11,1,123,261];
var arr32 = arrayRemoveRepeat(arr22,'number','');
console.log(arr32); // result is [12, 11, 212, 1243, 2321, 1, 123, 261];
1
2
3
4
5
6
7
8
9

# 检测函数参数是否为制定个数

function sum(x,y,z) {
    var sum = 0;
    if (arguments.length != 3) {
        throw new Error('必须是三个参数!');
    }
    for (let i = 0; i < arguments.length; i++) {
        const element = arguments[i];
        sum += element;
    }
    return sum;
}
1
2
3
4
5
6
7
8
9
10
11

实例:

var res = sum(1,2,3);
var res1 = sum(1,3);
console.log(res); // result is 6;
console.log(res1); // result is Uncaught Error: 必须是三个参数!
1
2
3
4

# 写在最后

上面就是我在日常使用中总结到的一些常用方法技巧。

分享至:

  • qq
  • qq空间
  • 微博
  • 豆瓣
  • 贴吧