在 JavaScript 中查詢字串中第一個重複字元的索引
需要我們撰寫一個 JavaScript 函式,該函式接收一個字串,並返回該字串中第一次出現的重複字元的索引。如果不存在這樣的字元,則應返回 -1。
假設我們的字串如下 −
const str = 'Hello world, how are you';
我們需要找出第一個重複字元的索引。
示例
程式碼如下 −
const str = 'Hello world, how are you'; const firstRepeating = str => { const map = new Map(); for(let i = 0; i < str.length; i++){ if(map.has(str[i])){ return map.get(str[i]); }; map.set(str[i], i); }; return -1; }; console.log(firstRepeating(str));
輸出
控制檯中的輸出為 −
2
廣告