使用 .forEach() 计算值出现在数组中的次数
Counting number of times value appears in an array using .forEach()
我正在尝试使用数组上的 .forEach 迭代器计算数组中的句子数。每次出现句号 ('.') 或感叹号 ('!') 时,它应该将计数器加 1。我想知道是否可以使用 Javascript 迭代器来做到这一点。
我过滤的数组叫做 betterWords。
下面的代码 returns 0 出于某种原因,我不确定为什么。
let sentences = 0;
betterWords.forEach(word => {
if (word === '.' || word === '!') {
return sentences+=1
}
});
console.log(sentences)
我了解到 OP 旨在通过计算 . ! ?
之类的句子终止标点符号来计算字符串中的句子数量(我错过了什么吗?)正则表达式匹配即可。数一下匹配项。
const countPunctuation = string => {
return (string.match(/[.!?]/g) || []).length
}
console.log(countPunctuation("This is a sentence. This is definitely a sentence! Is this a sentence?"))
您的解决方案几乎是正确的:
const betterWords = "Hello World! This is a nice text. Awesome!"
let sentences = 0;
betterWords.split('').forEach(word => {
if (word === '.' || word === '!') {
return sentences += 1
}
});
console.log(sentences)
您可以不运行 .forEach
字符串。您只能在数组上执行此操作。使用 split('')
,您可以 将字符串转换为数组 。 "ABC" => ["A", "B", "C"]
像@danh 那样使用 Regex 是解决这个问题的更快方法。
我正在尝试使用数组上的 .forEach 迭代器计算数组中的句子数。每次出现句号 ('.') 或感叹号 ('!') 时,它应该将计数器加 1。我想知道是否可以使用 Javascript 迭代器来做到这一点。
我过滤的数组叫做 betterWords。
下面的代码 returns 0 出于某种原因,我不确定为什么。
let sentences = 0;
betterWords.forEach(word => {
if (word === '.' || word === '!') {
return sentences+=1
}
});
console.log(sentences)
我了解到 OP 旨在通过计算 . ! ?
之类的句子终止标点符号来计算字符串中的句子数量(我错过了什么吗?)正则表达式匹配即可。数一下匹配项。
const countPunctuation = string => {
return (string.match(/[.!?]/g) || []).length
}
console.log(countPunctuation("This is a sentence. This is definitely a sentence! Is this a sentence?"))
您的解决方案几乎是正确的:
const betterWords = "Hello World! This is a nice text. Awesome!"
let sentences = 0;
betterWords.split('').forEach(word => {
if (word === '.' || word === '!') {
return sentences += 1
}
});
console.log(sentences)
您可以不运行 .forEach
字符串。您只能在数组上执行此操作。使用 split('')
,您可以 将字符串转换为数组 。 "ABC" => ["A", "B", "C"]
像@danh 那样使用 Regex 是解决这个问题的更快方法。