使用 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
廣告