面试题:
var obj = {
"2":'a',
"3":'b',
"length":2,
"push":Array.prototype.push
}
obj.push('c');
obj.push('d');
//{2: "c", 3: "d", length: 4, push: ƒ}
// Array.prototype.push = function(target){
// this[this.length] = target;
// this.length++;
// }
封装type
//封装type,实现以下返回值
//typeof([])--》array
//typeof({})--》object
//typeof(new Number())--》number - object
//typeof(new Boolean())--》boolean - object
//typeof(new String())--》string - object
function type(target){
var template = {
'[object Array]':'array',
'[object Object]':'object',
'[object Number]':'number - object',
'[object Boolean]':'boolean - object',
'[object String]':'string - object'
}
// 1.分两类:引用值 原始值
// 2.区分引用值
if(target === null){//处理特殊值
return 'null';
}else if(typeof(target) == 'object'){
//区分数组&对象&包装类
var str = Object.prototype.toString.call(target);
return template[str];
}else{
typeof(target);
}
}
数组去重
Array.prototype.unique = function() {
var obj = {
'push':Array.prototype.push,
'splice':Array.prototype.splice
}
var arr = [];
var len = this.length;
for(var i = 0; i < len; i++){
if(!obj[this[i]]){
obj[this[i]] = 'a';
arr.push(this[i]);
}
}
return arr;
}