JavaScript中的类数组,封装type函数,数组去重 |
您所在的位置:网站首页 › js封装函数数组去重 › JavaScript中的类数组,封装type函数,数组去重 |
类数组 1.可以利用属性名模拟数组的特性 2.可以动态的增长length属性 3.如果强行让数组调用push方法,则会根据length属性值进行属性的扩充 举例一 function test(){ console.log(arguments); //打印一个数组 arguments.push(7); //报错,说明arguments不是一个数组,不能使用数组所拥有的方法,而是类数组 } test(1,3,3,4,5,6);举例二 var obj = { //当调用obj.push('xxx')时,会像数组一样在数组结尾添加一个值,并且length的值自动加一 "0" : 'a', "1" : 'b', "2" : 'c', "length" : '3', "push" : Array.prototype.push } //属性要为索引(数字)属性,必须要有length属性,最好加上push在此基础之上再给数组添加一个splice方法,那么这个对象就跟数组一模一样了 var obj = { //当调用obj.push('xxx')时,会像数组一样在数组结尾添加一个值,并且length的值自动加一 "0" : 'a', "1" : 'b', "2" : 'c', "length" : '3', "push" : Array.prototype.push, "splice" : Array.prototype.splice } //属性要为索引(数字)属性,必须要有length属性,最好加上push举例三 var obj = { "2" : "a", "3" : "b", "length" : 2, "push" : Array.prototype.push } obj.push('c'); //push方法是根据length的长度来确定索引,因此下一个要加的是length为也就是第二位,覆盖掉之前的第二位a,同时length++ obj.push('d'); //同理覆盖掉第三位“b”,length++类数组的强大之处在于既可以当数组使用,还可以当对象使用,如下 var obj = { "0" : 'a', "1" : 'b', "2" : 'c', "name" : "abc", "age" : 123, "length" : '3', "push" : Array.prototype.push, "splice" : Array.prototype.splice }封装一个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"){ var str = Object.prototype.toString.call(target); return template[str]; }else{ return ret; } }数组去重 var arr = [1,2,1,5,8,8,7,9,5,8,9,10]; Array.prototype.unique = function(){ var temple ={}, arr = [], len = this.length; for(var i = 0; i < len ;i++){ if(!temple[this[i]]){ temple[this[i]] = "abc"; arr.push(this[i]); } } return arr; }
|
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |