var obj = {
"0": "a",
"1": "b",
"2": "c",
"length": 3,
}
var obj1 = {
"0": "a",
"1": "b",
"2": "c",
"length": 3,
"push": Array.prototype.push,
"splice": Array.prototype.splice
}
类数组要点:
1、必须要索引值的属性名 、数字
2、必须需要有length 属性
3、最好加上 push() 方法
4、选择性添加 splice()方法
类数组深入理解:
阿里试题:
var obj = {
"2": "a",
"3": "b",
"length": 2,
"push": Array.prototype.push,
}
obj.push("c");
obj.push("d");
打印出结果:
关键因素在于push()的执行原理
如下
Array.prototype.push = function(target) {
this[this.length] = target; //对于数组来讲 首先调用length 找到数组的末尾
length ++;
}
牢记push()原理即可
封装type函数
//封装type方法
function type(target) {
var tem = {
"[object Object]":"object-object",
"[object Array]":"Array",
"[object String]":"object-string",
"[object Boolean]":"object-boolean",
"[object Number]":"object-number"
},
toStr = Object.prototype.toString,
ret = typeof(target);
if(target === null) {
return 'null';
}else if(ret == 'object') {
var str = toStr.call(target);
return tem[str];
}else {
return ret;
}
}
封装数组去重(hash 原理 利用对象属性名唯一性)
Array.prototype.unique = function() {
var tem = {},
arr = [],
len = this.length;
for(var i = 0; i < len; i ++) {
if(!tem[this[i]]) {
tem[this[i]] = 333;
arr.push(this[i]);
}
}
return arr;
}
//原型链编程 可以数组直接调用