我有一個字串。
輸入 let s = aaabccddd
我想將此字串轉換為 obj 中的鍵-> 值對。
輸出 讓 obj = { a:3, b:1, c:2, d:3 }
我知道如何制作鑰匙,但對價值感到困惑,請提供 javascript 解決方案,謝謝
uj5u.com熱心網友回復:
只需遍歷字串并為每個字符在單獨的物件中增加一個計數器。
function countOccurences(string) {
const result = {};
for (const character of string) {
if (typeof result[character] === 'undefined') {
result[character] = 0;
}
result[character] ;
}
return result;
}
console.log(countOccurences('aaabccddd'));
//=> {a: 3, b: 1, c: 2, d: 3}
uj5u.com熱心網友回復:
這可以通過Array.reduce()以下方式完成:
let s = 'aaabccddd';
let result = [...s].reduce((o, c) => {
o[c] = (o[c] | 0) 1;
return o;
}, {});
console.log(result);
uj5u.com熱心網友回復:
您可以使用Function.prototype.call在字串上呼叫Array.prototype.reduce方法,并按字符的出現對字符進行分組。
const
str = "aaabccddd",
res = Array.prototype.reduce.call(
str,
(r, s) => {
r[s] ??= 0;
r[s] = 1;
return r;
},
{}
);
console.log(res);
其他相關檔案:
- 空值合并運算子 (??)
uj5u.com熱心網友回復:
您可以使用String.match()RegExp 來獲取每個字符的重復出現,將它們映射到[character, occurrences]對陣列,并使用以下方法將對串列轉換為物件Object.fromEntries():
const fn = s => Object.fromEntries(s
.match(/(.)\1*/g) // find all recuring matches
.map(str => [str[0], str.length]) // create an array of [character, occurrences]
)
const s = 'aaabccddd'
const result = fn(s)
console.log(result)
或使用String.matchAll()withArray.from()創建條目串列:
const fn = s => Object.fromEntries(
Array.from(
s.matchAll(/(.)\1*/g), // find all recuring matches
([{ length }, c]) => [c, length] // create an array of [character, occurrences]
)
)
const s = 'aaabccddd'
const result = fn(s)
console.log(result)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/483559.html
標籤:javascript 数组 细绳 目的
上一篇:按屬性值顯示物件
