常用工具方法

时间:2022-08-31 17:34:49

扩展trim方法

String.prototype.trim = String.prototype.trim || function(str) {
return this.replace(/^\s+|\s+$/g, '');
};

判定当前是iOS环境

var isIos = function() {
var ua = navigator.userAgent;
if(ua.match(/(iPhone\sOS)\s([\d_]+)/) || ua.match(/(iPad).*OS\s([\d_]+)/)) {
return true;
} else {
return false;
}
};

截取location.search中的参数信息

var getUrlParam = function(str, param) {
str = str.replace(/.*\?/, '');
var paramList = str.split('&');
var obj = {};
for(var i = 0, len = paramList.length; i < len; i++) {
var item = paramList[i].split('=');
obj[item[0]] = item[1];
}
if(param) {
return obj[param];
} else {
return obj;
}
};

合并对象

var isObject = function(obj) {
return obj !== null && typeof obj === 'object' && Object.getPrototypeOf(obj) === Object.prototype;
};
var extend = function(target, obj) {
for(var param in obj) {
var src = target[param];
var copy = obj[param];
if(src === copy) {
continue;
}
if(isObject(copy)) {
src = src || {};
target[param] = extend(src, copy);
} else {
target[param] = copy;
}
}
return target;
};

获取对象的类型

var type = function(obj){
return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
};