最新文章专题视频专题问答1问答10问答100问答1000问答2000关键字专题1关键字专题50关键字专题500关键字专题1500TAG最新视频文章推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37视频文章20视频文章30视频文章40视频文章50视频文章60 视频文章70视频文章80视频文章90视频文章100视频文章120视频文章140 视频2关键字专题关键字专题tag2tag3文章专题文章专题2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章专题3
当前位置: 首页 - 科技 - 知识百科 - 正文

js实现数组去重、判断数组以及对象中的内容是否相同_javascript技巧

来源:懂视网 责编:小采 时间:2020-11-27 21:16:38
文档

js实现数组去重、判断数组以及对象中的内容是否相同_javascript技巧

js实现数组去重、判断数组以及对象中的内容是否相同_javascript技巧: 代码如下: /* *数组元素去重 */ if(typeof Array.prototype.distinct != function){ Array.prototype.distinct = function(){ this.sort(); for(var i=0;iif($.isPlainObject(this[i]) && $.isPla
推荐度:
导读js实现数组去重、判断数组以及对象中的内容是否相同_javascript技巧: 代码如下: /* *数组元素去重 */ if(typeof Array.prototype.distinct != function){ Array.prototype.distinct = function(){ this.sort(); for(var i=0;iif($.isPlainObject(this[i]) && $.isPla

代码如下:
/*
*数组元素去重
*/
if(typeof Array.prototype.distinct != "function"){
Array.prototype.distinct = function(){
this.sort();
for(var i=0;iif($.isPlainObject(this[i]) && $.isPlainObject(this[i+1])){
if(o2o(this[i],this[i+1])){
this.splice(i,1);
}
}else if($.isArray(this[i]) && $.isArray(this[i+1])){
if(a2a(this[i],this[i+1])){
this.splice(i,1);
}
}else if(this[i]===this[i+1]){
this.splice(i,1);
}
}
}
}
/*
*比较对象是否相同
*/
function o2o(o1,o2){
if(!($.isPlainObject(o1) && $.isPlainObject(o2))){
return false;
}

var k1k2=[],k1 =[],k2=[];
$.each(o1,function(k,v){
k1.push(k);
});

$.each(o2,function(k,v){
k2.push(k);
});
if(k1.length != k2.length){
return false;
}
k1k2 = k1;
k1k2 = k1k2.concat(k2);
k1k2.distinct();
if(k1.length != k1k2.length || k2.length != k1k2.length){
return false;
}

var flag=true;
$.each(k1k2,function(i,v){
var v1= o1[v];
var v2 =o2[v];
if(typeof v1 != typeof v2){
flag= false;
}else{
if($.isPlainObject(v1) && $.isPlainObject(v2)){//recursion
flag = o2o(v1,v2);
if(!flag){
return false;
}
}else if($.isArray(v1) && $.isArray(v2)){
flag = a2a(v1,v2);
if(!flag){
return false;
}
}else{
if(v1 !== v2){
flag= false;
}
}
}
});
return flag;
}
/*
*比较数组是否完全相同
*/
function a2a(a1,a2){
if(!($.isArray(a1) && $.isArray(a2))){
return false;
}
if(a1.length != a2.length){
return false;
}

a1.sort();
a2.sort();
for(var i=0;iif(typeof a1[i] != typeof a2[i]){
return false;
}
if($.isPlainObject(a1[i]) && $.isPlainObject(a2[i])){
var retVal = o2o(a1[i],a2[i]);
if(!retVal){
return false;
}
}else if($.isArray(a1[i]) && $.isArray(a2[i]) ){//recursion
if(!a2a(a1[i],a2[i])){
return false;
}
}else if(a1[i] !== a2[i]){
return false;
}
}
return true;
}

文档

js实现数组去重、判断数组以及对象中的内容是否相同_javascript技巧

js实现数组去重、判断数组以及对象中的内容是否相同_javascript技巧: 代码如下: /* *数组元素去重 */ if(typeof Array.prototype.distinct != function){ Array.prototype.distinct = function(){ this.sort(); for(var i=0;iif($.isPlainObject(this[i]) && $.isPla
推荐度:
标签: 是否 js 相同
  • 热门焦点

最新推荐

猜你喜欢

热门推荐

专题
Top