贴几个常用的基础函数
取自jsGen的tool.js
function isArray(obj) { return Array.isArray ? Array.isArray(obj) : Object.prototype.toString.call(obj) === '[object Array]'; } function isNull(obj) { return obj === null || obj === undefined || obj !== obj; } function toStr(value) { return isNull(value) ? '' : value + ''; } function hasOwn(obj, key) { return Object.prototype.hasOwnProperty.call(obj, key); } function isEmpty(obj) { for (var key in obj) { if (hasOwn(obj, key)) { return false; } } return true; } function checkType(obj) { var type = typeof obj; if (obj === null) { return 'null'; } else if (isArray(obj)) { return 'array'; } else { return type; } } function trim(str, strict) { return toStr(str). replace(strict ? (/\s+/g) : (/ +/g), ' '). replace(/^\s+/, ''). replace(/\s+$/, ''); } function each(obj, iterator, context, arrayLike, right) { iterator = iterator || angular.noop; if (!obj) { return; } else if (arrayLike || isArray(obj)) { if (!right) { for (var i = 0, l = obj.length; i < l; i++) { if (iterator.call(context, obj[i], i, obj) === breaker) { return; } } } else { for (var i = obj.length - 1; i >= 0; i--) { if (iterator.call(context, obj[i], i, obj) === breaker) { return; } } } } else { for (var key in obj) { if (hasOwn(obj, key)) { if (iterator.call(context, obj[key], key, obj) === breaker) { return; } } } } }
// 去除数组中的undefined值,修改原数组,返回原数组 function digestArray(list) { var result = []; if (isArray(list)) { each(list, function (x, i) { if (checkType(x) === 'undefined') { list.splice(i, 1); } }, null, true, true); } return list; }