JavaScript如何比较两个数组的内容是否相同

JavaScript017

JavaScript如何比较两个数组的内容是否相同,第1张

Javascript不能直接用==或者===来判断两个数组是否相等,无论是相等还是全等都不行,以下两行JS代码都会返回false<script type="text/javascript">alert([]==[])alert([]===[])</script>要判断JS中的两个数组是否相同,需要先将数组转换为字符串,再作比较。以下两行代码将返回true<script type="text/javascript">alert([].toString()== [].toString())alert([].toString()===[].toString())</script>JS要比较两个数组是否有相同的元素,即两个数组所有元素都相同,但元素的顺序不一定一致。只就需要先将数组进行排序,再比较两个数组是否相等。试比较以下两行代码:<script type="text/javascript">alert([1,2,3].toString()== [3,2,1].toString())alert([1,2,3].sort().toString()== [3,2,1].sort().toString())</script>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

</head>

<body>

<script>

//做比较的两个数组

var array1 = ['a','b','c','d']//数组1 (所有人)

var array2 = ['a','d']//数组2 (需要删除的人)

//临时数组存放

var tempArray1 = []//临时数组1

var tempArray2 = []//临时数组2

for(var i=0i<array2.lengthi++){

tempArray1[array2[i]]=true//将数array2 中的元素值作为tempArray1 中的键,值为true;

}

for(var i=0i<array1.lengthi++){

if(!tempArray1[array1[i]]){

tempArray2.push(array1[i])//过滤array1 中与array2 相同的元素;

}

}

console.log(tempArray2)

const arrAll = [

{

name: 'a',

code: 'aa',

config: false

},

{

name: 'b',

code: 'bb',

config: true

},

{

name: 'c',

code: 'cc',

config: false

},

{

name: 'd',

code: 'dd',

config: false

}

]

let newarr3 = []

arrAll.map(item =>{

array2.map(list =>{

if (item.name === list) {

newarr3.push({

name: list,

config: true,

code: item.code

})

}

})

})

console.log('333', newarr3)

let newarr4 = []

arrAll.map(item =>{

tempArray2.map(list =>{

if (item.name === list) {

newarr4.push({

name: list,

config: false,

code: item.code

})

}

})

})

console.log('444', newarr4)

console.log('newall', [...newarr3, ...newarr4])

const newarrAll = [...newarr3, ...newarr4]

const newarr5 = []

arrAll.map(item =>{

newarrAll.map(list =>{

if (item.name === list.name) {

newarr5.push({

name: item.name,

config: list.config,

code: item.code

})

}

})

})

console.log('5555', newarr5)

let ques= [

{a:2,b:2},

{a:2, b:2}]

console.log([...new Set(ques.map(e =>JSON.stringify(e)))].map(e =>JSON.parse(e)))

</script>

</body>

</html>