深克隆
function deepClone (origin, target) {
// 目标,类型判断,数组类型对比
var target = target || {},
toStr = Object.prototype.toString(),
arrStr = '[object Array]';
// 遍历对象属性
for (var prop in origin) {
if (origin.hasOwnPropertyOf(prop)) {
if (origin[prop] !== null && typeof origin[prop] === 'object') {
// 引用类型
target[prop] = toStr.call(origin[prop]) === arrStr ? [] : {}
deepClone(origin[prop], target[prop]);
} else {
// 原始类型
target[prop] = origin[prop];
}
}
}
return target;
}
type方法重构
function type (target) {
var ret = typeof target;
var template = {
'[object Array]': 'array',
'[object Object]': 'object',
'[object Number]': 'number - object',
'[object Boolean]': 'boolean - object',
'[object String]': 'string - object',
}
if (target === null) {
return 'null'
} else if (ret === 'object') {
return template[Object.prototype.toString.call(target)];
} else {
return ret;
}
}
数组
- 改变原数组
- push、pop、unshift、shift、reverse、sort
- splice
- 返回新数组
// 有序数组乱序
[1, 2, 3].sort(function () {
return 0.5 - Math.random()
})
类数组
// 类数组
var arrLike = {
'0': 'a',
'1': 'b',
'2': 'c',
'length': 3,
push: Array.prototype.push,
splice: Array.prototype.splice,
}
// 考题
var obj = {
2 :'a',
3: 'b',
length: 2,
push: Array.prototype.push,
}
obj.push('c')
obj.push('d')
// {2: "c", 3: "d", length: 4}
数组去重
Array.prototype.unique = function () {
var temp = {},
arr = [],
len = this.length;
for (var i = 0; i < len; i++) {
if (!temp[this[i]]) {
temp[this[i]] = 'abc';
arr.push(this[i]);
}
}
}
网友评论