zoukankan      html  css  js  c++  java
  • JavaScript的灵活应用

    1、查找数组的最大值和最小值

    (1)
    Math.max.qpply(null,array);
    Math.min.qpply(null,array);
    (2)
    eval("Math.max("+array.toString()+")")
    eval("Math.min("+array.toString()+")")
    (3)
    ary.sort(function(a,b){
    	return a-b;
    })
    (4)
    let max=array[0],min=array[0];
    for(let i=1;i<array.length;i++){
    	let cur=array[i];
    	max<cur?max=cur:null;
    	min>cur?min=cur:null;
    }
    

    2.转化一个数字数组为function数组(每个function都弹出相应的数字)

    var a = [111, 2, 6, 4, 22, 5, 99, 3];
    a = a.map(function (value) {
        return function () {
            return value;
        }
    });
    console.log(a[2]());
    

    3.给object数组进行排序(排序条件是每个元素对象的属性个数)

    var b = [{a: 1, b: 2}, {a: 1, b: 2, c: 3, d: 5}, {a: 1}, {a: 1, b: 2, c: 3, d: 4}];
    //拓展count方法
    Object.prototype.count = (
        Object.prototype.hasOwnProperty('_count_') ?
            function () {
                return this._count_;
            } :
            function () {
                var p, count = 0;
                for (p in this) {
                    if (this.hasOwnProperty(p)) {
                        count++;
                    }
                }
                return count;
            }    );
    function compare(obj1, obj2) {
        return obj1.count() - obj2.count();
    }
    console.log(b.sort(compare));
    

    4.实现如下语法的功能:var a = add(2)(3)(4);怎么实现可以一直不停地累加呢?

    function add(x) {
        var sum = x;
        var fn = function (y) {
            sum += y;
    
            return fn;
        };
        fn.valueOf = fn.toString = function () {
            return sum;
        };
        return fn;
    }
    console.log((add(2)(4)).toString());//6
    console.log(add(2));//function 2
    console.log(add(3)(8)(9));//function 20
    console.log(add(3)(8)(9)(10));//function 30
    
  • 相关阅读:
    小波变换的引入,通俗易懂
    Leetcode 437. Path Sum III
    Leetcode 113. Path Sum II
    Leetcode 112 Path Sum
    Leetcode 520 Detect Capital
    Leetcode 443 String Compression
    Leetcode 38 Count and Say
    python中的生成器(generator)总结
    python的random模块及加权随机算法的python实现
    leetcode 24. Swap Nodes in Pairs(链表)
  • 原文地址:https://www.cnblogs.com/Juphy/p/7087951.html
Copyright © 2011-2022 走看看