使用 JavaScript 檢查字串是否包含所有唯一字元


問題

我們需要編寫一個 JavaScript 函式,它接收一個 Sting 並返回 true(如果字串中的所有字元均僅出現一次)或 false(字串中的某些字元出現多次)。

示例

以下為程式碼 −

 動態演示

const str = 'thisconaluqe';
const allUnique = (str = '') => {
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      if(str.indexOf(el) !== str.lastIndexOf(el)){
         return false;
      };
   };
   return true;
};
console.log(allUnique(str));

輸出

true

更新於: 19-4-2021

292 條瀏覽量

職業一蹴而就

完成課程以獲得認證

開始學習
廣告