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