如何比较两个字符串数组,不区分大小写且与 JavaScript、ES6 的排序无关

javascriptweb developmentobject oriented programming更新于 2025/9/28 16:44:17

我们需要编写一个函数,例如 isEqual(),该函数接受两个字符串作为参数,并检查它们是否都包含相同的字符,而与它们的顺序和大小写无关。

例如 −

const first = 'Aavsg';
const second = 'VSAAg';
isEqual(first, second); //true

方法:1 使用数组

在此方法中,我们将字符串转换为数组,使用 Array.prototype.sort() 方法,将它们转换回字符串并检查是否相等。

其代码为 −

示例

const first = 'Aavsg';
const second = 'VSAAg';
const stringSort = function(){
   return this.split("").sort().join("");
}
String.prototype.sort = stringSort;
const isEqual = (first, second) => first.toLowerCase().sort() ===
second.toLowerCase().sort();
console.log(isEqual(first, second));

方法 2:使用 Map

在此方法中,我们同时迭代两个字符串,将字符频率存储在具有如下值的 Map 中−

-1, if it appears in the first string,
+1, if it appears in the second string,

最后,如果所有键的值加起来为 0,则认为字符串相同,否则不相同。

其代码为 −

示例

const first = 'Aavsg';
const second = 'VSAAg';
const isEqual = (first, second) => {
   if(first.length !== second.length){
      return false;
   }
   first = first.toLowerCase();
   second = second.toLowerCase();
   const map = {};
   for(ind in first){
      if(map[first[ind]]){
         map[first[ind]]++;
      }else{
         map[first[ind]] = 1;
      }
      if(map[second[ind]]){
         map[second[ind]]--;
      }else{
         map[second[ind]] = -1;
      }
   };
   return Object.values(map).reduce((acc, val) => val === 0 && acc, true);
};
console.log(isEqual(first, second));

输出

两者的控制台输出均为 −

true

相关文章


有用资源