1、数组去重:
constset=newSet([1,2,3,4,4]);
[...set]// [1, 2, 3, 4]
2、常见数据类型判断和转换, 参考链接
数组判断:
function isArray(val) {
return toString.call(val) ==='[object Array]';
}
Buffer 判断:
function isArrayBuffer(val) {
return toString.call(val) ==='[object ArrayBuffer]';
}
字符串判断:
function isString(val) {
return typeof val ==='string';
}
数字判断:
function isNumber(val) {
return typeof val ==='number';
}
对象判断:
function isObject(val) {
return val !==null &&typeof val ==='object';
}
日期判断:
function isDate(val) {
return toString.call(val) ==='[object Date]';
}
文件判断:
function isFile(val) {
return toString.call(val) ==='[object File]';
}
函数判断:
function isFunction(val) {
return toString.call(val) ==='[object Function]';
}
首尾去空格:
function trim(str) {
return str.replace(/^\s*/, '').replace(/\s*$/, '');
}
对象数组遍历:为对象和数组的每个属性执行回调,回调的入参为属性值,key or index,对象或数组:
function forEach(obj, fn) {
// Don't bother if no value provided
if (obj ===null ||typeof obj ==='undefined') {
return;
}
// Force an array if not already something iterable
if (typeof obj !=='object') {
/*eslint no-param-reassign:0*/
obj = [obj];
}
if (isArray(obj)) {
// Iterate over array values
for (var i =0, l = obj.length; i < l; i++) {
fn.call(null, obj[i], i, obj);
}
}else {
// Iterate over object keys
for (var keyin obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
fn.call(null, obj[key], key, obj);
}
}
}
}
对象浅拷贝
function merge(/* obj1, obj2, obj3, ... */) {
var result = {};
function assignValue(val, key) {
if (typeof result[key] ==='object' &&typeof val ==='object') {
result[key] =merge(result[key], val);
}else {
result[key] = val;
}
}
for (var i =0, l = arguments.length; i < l; i++) {
forEach(arguments[i], assignValue);
}
return result;
}
对象深拷贝:
function deepMerge(/* obj1, obj2, obj3, ... */) {
var result = {};
function assignValue(val, key) {
if (typeof result[key] ==='object' &&typeof val ==='object') {
result[key] =deepMerge(result[key], val);
}else if (typeof val ==='object') {
result[key] =deepMerge({}, val);
}else {
result[key] = val;
}
}
for (var i =0, l = arguments.length; i < l; i++) {
forEach(arguments[i], assignValue);
}
return result;
}
解析 location.search
var oGetVars={};
if(window.location.search.length>1){
for(varaItKey, nKeyId=0, aCouples=window.location.search.substr(1).split("&"); nKeyId aItKey=aCouples[nKeyId].split("="); oGetVars[decodeURIComponent(aItKey[0])] = aItKey.length > 1 ? decodeURIComponent(aItKey[1]) : "";} }