方法一:

1
2
3
4
5
6
7
8
9
10
11
12
let flag = true
const listA = [1, 2, 3]
const listB = [2, 3, 4]
if (listA.length !== listB.length) {
flag = false
} else {
listA.forEach(item => {
if (listB.indexOf(item) === -1) {
flag = false
}
})
}

方法二:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function isSame (a, b) {
if (a.length !== b.length) return false

let c = b.slice()
// 在可以提前退出的情况下不要使用forEach
for (let i = 0, len = a.length; i < len; i++) {
let j = c.indexOf(a[i])
if ( j === -1) return false
c.splice(j, 1) // 删除已经匹配的元素,可以缩短下次匹配的时间
}
return true
}
isSame([1, 2, 2], [1, 1, 2]) // false
isSame([1, 2, 2], [2, 1, 2]) // true

其他方法:

1
2
3
4
5
6
7
const listA = [1, 2, 3]
const listB = [2, 3, 1]

const result = listA.length === listB.length && listA.every(a => listB.some(b => a === b)) && listB.every(_b => listA.some(_a => _a === _b));

console.log(result);
//true

当内容为字符串:

1
2
3
4
5
6
function isEqual(arr1, arr2) {
return JSON.stringify(arr1.sort()) === JSON.stringify((arr2.sort()))
}

// true
isEqual([1, 5, 'string', 2], [1, 2, 5, 'string'])