在 JavaScript 中检查两个数组的值是否相同/相等
javascriptweb developmentobject oriented programming更新于 2025/10/3 3:24:17
我们有两个数字数组,假设为 −
[2, 4, 6, 7, 1] [4, 1, 7, 6, 2]
假设,我们必须编写一个函数,该函数基于它们是否包含相同元素(无论其顺序如何)返回布尔值。
例如 −
[2, 4, 6, 7, 1] 和 [4, 1, 7, 6, 2] 应该返回 true,因为它们具有相同的元素,但顺序不同。
现在,让我们为该函数编写代码 −
示例
const first = [2, 4, 6, 7, 1];
const second = [4, 1, 7, 6, 2];
const areEqual = (first, second) => {
if(first.length !== second.length){
return false;
};
for(let i = 0; i < first.length; i++){
if(!second.includes(first[i])){
return false;
};
};
return true;
};
console.log(areEqual(first, second));
输出
控制台中的输出将是 −
true
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

