我有這個字串:
item_type = 'a, a, b'
我怎樣才能計算這些值,所以我會得到這樣的東西:
number_of_a = 2
number_of_b = 1
我嘗試了類似下面的操作,但輸入字串“[object Object]”錯誤時得到了一些javascript
if(item_type != null) {
item_type = item_type.split(",");
item_type.forEach(function(x) {
number_of_a[x] = (number_of_a[x] || 0) 1;
});
}
uj5u.com熱心網友回復:
你可以用一個簡單的回圈來做到這一點:
const str = 'a, a, b'
const chars = {}
for (let char of str) {
chars[char] = chars[char] 1 || 1;
}
console.log(chars)
uj5u.com熱心網友回復:
reduce 是您的朋友,就像任何分組操作一樣
const item_type = 'a, a, b';
const result = item_type.split(", ").reduce ( (a,i) => {
a[i] = (a[i] 1 || 1)
return a;
},{})
console.log(result);
uj5u.com熱心網友回復:
如果我們只對字母感興趣,請改進@Tamas Szoke 的答案。
const str = 'a, a, b'
const chars = {}
for (let char of str) {
if(char.toUpperCase() != char.toLowerCase()){
chars[char] = chars[char] 1 || 1;
}
}
console.log(chars)
uj5u.com熱心網友回復:
如果可能只有a或者b你可以這樣做:
const item_type = 'a, a, b'
let number_of_a = 0
let number_of_b = 0
if (item_type != null) {
item_type
.split(',')
.map(el => el.trim()) //remove whitespaces from each element
.forEach(el => el === 'a' ? number_of_a : number_of_b )
}
console.log(`a: ${number_of_a}`)
console.log(`b: ${number_of_b}`)
否則,您應該使用陣列或物件:
const item_type = 'a, a, b'
const occurrences = {}
if (item_type != null) {
item_type
.split(',')
.map(el => el.trim()) //remove whitespaces from each element
.forEach(el => {
if (!occurrences[el]) {
occurrences[el] = 1
} else {
occurrences[el] = 1
}
})
}
for (const [key, value] of Object.entries(occurrences)) {
console.log(`${key}: ${value}`)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/352577.html
標籤:javascript
上一篇:在瀏覽器上臨時存盤資料
下一篇:如何每天自動點擊網站上的按鈕
