You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

使用JavaScript迭代器处理文本遇异常,请求代码调试帮助

问题分析与解决方案

嘿,我仔细看了你的代码,发现两个核心问题导致结果不符合预期,咱们一步步来修复:

1. 字符串拆分方式错误

你当前用了 story.split(""),这会把字符串每个单独字符拆分成数组元素(比如把"Last"拆成['L','a','s','t']),所以storyWords.length显示的是总字符数978,而不是单词数。这直接导致后续的过滤和统计都基于字符数组,完全无法匹配你定义的单词列表。

修复方法:按空格拆分单词,推荐用正则表达式/\s+/来处理多个连续空格的情况,避免生成空字符串元素:

let storyWords = story.split(/\s+/);

2. 单词与标点粘连导致匹配失败

原文里很多单词后面跟着标点(比如really,actually!),直接用includes()匹配overusedWordsunnecessaryWords里的纯单词会完全匹配不到,这就是为什么totalUsed是0,且betterWords没有过滤掉任何内容的原因。

修复方法:先清洗每个单词,去掉附带的标点符号,再进行判断:

修正后的完整代码

let story = 'Last weekend, I took literally the most beautiful bike ride of my life. The route is called "The 9W to Nyack" and it actually stretches all the way from Riverside Park in Manhattan to South Nyack, New Jersey. It\'s really an adventure from beginning to end! It is a 48 mile loop and it basically took me an entire day. I stopped at Riverbank State Park to take some extremely artsy photos. It was a short stop, though, because I had a really long way left to go. After a quick photo op at the very popular Little Red Lighthouse, I began my trek across the George Washington Bridge into New Jersey. The GW is actually very long - 4,760 feet! I was already very tired by the time I got to the other side. An hour later, I reached Greenbrook Nature Sanctuary, an extremely beautiful park along the coast of the Hudson. Something that was very surprising to me was that near the end of the route you actually cross back into New York! At this point, you are very close to the end.';
let overusedWords = ["really", "very", "basically"];
let unnecessaryWords = ["extremely", "literally", "actually"];

// 按空格拆分单词,处理多空格情况
let storyWords = story.split(/\s+/);
console.log(storyWords.length); // 现在输出的是单词数,约120左右

// 过滤不必要的单词,先清洗标点
let betterWords = storyWords.filter(function(word) {
  // 去掉单词中的标点:.,!?""等,转小写确保匹配(可选,原文都是小写)
  const cleanWord = word.replace(/[.,!?"]/g, '').toLowerCase();
  return !unnecessaryWords.includes(cleanWord);
});
console.log(betterWords); // 现在会移除掉unnecessaryWords里的单词

// 统计过度使用的单词次数
let totalUsed = 0;
for (let word of betterWords) {
  const cleanWord = word.replace(/[.,!?"]/g, '');
  if (overusedWords.includes(cleanWord)) {
    totalUsed++;
  }
}
// 或者用更简洁的reduce写法:
// const totalUsed = betterWords.reduce((count, word) => {
//   const cleanWord = word.replace(/[.,!?"]/g, '');
//   return overusedWords.includes(cleanWord) ? count + 1 : count;
// }, 0);

console.log(totalUsed); // 现在会输出正确的次数:9

验证结果

  • betterWords会成功移除extremelyliterallyactually这些单词
  • totalUsed会统计到really(3次)、very(5次)、basically(1次),总共9次

内容的提问来源于stack exchange,提问作者Jonathan Sexton

火山引擎 最新活动