Home > Web Front-end > JS Tutorial > Methods for simulating map output and removing duplicates in javascript_javascript skills

Methods for simulating map output and removing duplicates in javascript_javascript skills

WBOY
Release: 2016-05-16 16:15:06
Original
2307 people have browsed it

The example in this article describes the method of javascript simulating map output and removing duplicates. Share it with everyone for your reference. The specific method is as follows:

1.Javascriptmap output

function Map(){ 
// private  
var obj = {} ;// 空的对象容器,承装键值对 
// put 方法 
this.put = function(key , value){ 
 obj[key] = value ;// 把键值对绑定到obj对象上
} 
// size 方法 获得map容器的个数 
this.size = function(){ 
 var count = 0 ;  
 for(var attr in obj){ 
   count++; 
 } 
 return count ;  
} 
// get 方法 根据key 取得value 
this.get = function(key){ 
  if(obj[key] || obj[key] === 0 || obj[key] === false){ 
 return obj[key]; 
  } else { 
 return null; 
  } 
} 
//remove 删除方法 
this.remove = function(key){ 
  if(obj[key] || obj[key] === 0 || obj[key] === false){ 
 delete obj[key];             
  } 
} 
// eachMap 变量map容器的方法 
this.eachMap = function(fn){ 
 for(var attr in obj){ 
   fn(attr, obj[attr]); 
 } 
} 
} 
//模拟java里的Map 
var m = new Map(); 
m.put('01' , 'abc'); 
m.put('02' , false) ; 
m.put('03' , true); 
m.put('04' , new Date()); 

//alert(m.size()); 

//alert(m.get('02')); 
//m.remove('03'); 
//alert(m.get('03')); 

m.eachMap(function(key , value){ 
     alert(key +" :"+ value); 
});
Copy after login

2. Remove duplicate items in the map

var arr = [2,1,2,10,2,3,5,5,1,10,13];//object 
//js对象的特性:在js对象中key是永远不会重复的  
/* 
var obj = new Object(); 
obj.name = 'z3'; 
obj.age = 20 ; 
//alert(obj.name); 
obj.name = 'w5'; 
alert(obj.name); 
*/ 
 
// 1 把数组转成一个js的对象 
// 2 把数组中的值,变成js对象当中的key 
// 3 把这个对象 再还原成数组 
 
// 把数组转成对象 
function toObject(arr){ 
 var obj = {} ; // 私有的对象 
 var j ; 
 for(var i=0 , j= arr.length ; i<j; i++){ 
 obj[arr[i]] = true ; 
 } 
 return obj ; 
} 
 
// 把这个对象转成数组 
function keys(obj){ 
 var arr = [] ; // 私有对象 
 for(var attr in obj){ 
   if(obj.hasOwnProperty(attr)){//YUI底层代码 
 arr.push(attr); 
   } 
 } 
 return arr ; 
} 

//综合的方法 去掉数组中的重复项 
function uniq(newarr){ 
 return keys(toObject(newarr)); 
} 
alert(uniq(arr));
Copy after login

I hope this article will be helpful to everyone’s JavaScript programming design.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template