這個問題在這里已經有了答案: Javascript 中的經典字數演算法 3 個答案 8 小時前關閉。
我正在嘗試創建一個將字串作為輸入的函式。這個函式應該計算每個單詞并在單個單詞旁邊顯示一個計數。單詞的每次迭代計數應該增加。
輸入在哪里,string == "this is this sample"預期輸出在哪里"this(2) is(1) this(2) sample(1)"
這是我到目前為止所擁有的:
function wordCounter(string) {
const array = string.split(" ");
let count = 0;
for (let i = 0; i < array.length; i ) {
// if statement? //
}
}
據我了解,字串需要轉換為要回圈的陣列。但是,我很難理解每個特定單詞如何有自己的計數器。我也研究了 .reduce(),但很難實作它。
uj5u.com熱心網友回復:
我的第一個原始想法是做這樣的事情:
function wordCounter(string) {
const array = string.split(" ");
let count = {};
let result = '';
for (let i = 0; i < array.length; i ) {
if(count[array[i]]) {
count[array[i]] =1;
} else {
count[array[i]] = 1;
}
}
Object.keys(count).map(key => {
result = key '(' count[key] ') ';
});
return result;
}
console.log(wordCounter('hello this is a test'));
uj5u.com熱心網友回復:
這似乎可行,但請注意,它的編碼目的是不計算空格,并且在考慮字數時包括標點符號/大小寫。
function wordCounter(string) {
var array = string.split(" ");
//"dictionary" is an object. We'll store words in it like properties.
var dictionary = {};
var final = "";
var current;
var currentCount;
for (let index = 0; index < array.length; index ) {
current = array[index];
//If the current array item isn't a blank...
if (current != "") {
//If the word isn't already in dictionary...
if (dictionary[current] == null) {
//We add it and set it to 1.
currentCount = 1;
dictionary[current] = currentCount;
}
//Otherwise...
else {
//We get the current value, add 1, and set the property to the new value.
currentCount = dictionary[current] 1;
dictionary[current] = currentCount;
}
//Now we append the word, parentheses, and current count.
final = current "(" currentCount ") ";
}
}
//Once the loops is done, if our word is greater than 0 characters, we slice the last one (the extra space from our last iteration).
if (final.length > 0) {
final = final.slice(0, -1);
}
//Print the final text.
alert(final);
}
window.addEventListener('load', function() {
wordCounter("This right here is this the sample of the sample you wanted. It's not the same as your sample, but it's a sample none the less.");
wordCounter("");
wordCounter(" ");
wordCounter(" this this and this ");
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/420756.html
標籤:
