js 常用函数收集(基础)

(1)、判断是否为数值

function isNum(obj){
  return !isNaN(parseFloat(obj)) && isFinite(obj);
}

 

(2)、判断是否为数值

function isEmptyObject(){
  var name;
//遍历不是空对象返回 for (name in obj) { return false; } return true; }

 

(3)、随机一个整数

function select(start, end) {
  var total = end - start +1;
  return Math.floor(Math.random() * total + start);
}

 

(4)、检查对象类型

      检测obj对象类型,返回类型,通过Object.prototype.toString()来判断类型,但是ie低版本兼容性有问题,因此采用{}.toString来监测,返回为[object Array],[object Object],[object Function]

// 类型判断
function isType(type){
    return function(o){
        return Object.prototype.toString.call(o) === '[object ' + type + ']';
    }
}

var isString = isType(“String”);
var isObject = isType("Object");
var isArray = isType("Array");
 
isString("I'm Barret Lee.");
isArray([1,2,3]);
isObject({});

 

(5)、用_$(id)代替document.getElementById(id).

function $(objectId) {
if(document.getElementById && document.getElementById(objectId)) {
    return document.getElementById(objectId);// W3C DOM
    } else if (document.all && document.all(objectId)) {
        return document.all(objectId);// MSIE 4 DOM
    } else if (document.layers && document.layers[objectId]) {
        return document.layers[objectId];// NN 4 DOM.. note: this won't find nested layers
    } else {
        return false;
    }
}

 

(6)、js获取行内属性

function getStyle(obj, attr){  
    if(obj.currentStyle){  
        return obj.currentStyle[attr];  
    }  
    else{  
        return getComputedStyle(obj,false)[attr];  
    }  
}

 

posted @ 2015-07-21 11:43  web前端学习  阅读(254)  评论(0编辑  收藏  举报