首页 > 解决方案 > 为什么这不可能: let array[j] = array[j] + 1;

问题描述

如果单词存在于数组中。创建存储该单词在数组中出现的次数的变量。当我运行它时,我收到错误 Unexpected token。如果 newStory[i] 等于 overusedWords[j] 创建一个变量 overusedWords[j] 并为其添加 +1。

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']
const newStory = story.split(" ");

//Here we find the number of times overusedWords are used specifically in story
for (let i = 0; i <= newStory.length; i++) {
  for(let j = 0; j <= overusedWords.length; j++){
	if(newStory[i] === overusedWords[j]){
	  let overusedWords[j] = overusedWords[j] + 1;
	};
  };
};

标签: javascriptarrays

解决方案


您不能创建名称包含 [ 字符的变量

您在应用程序中使用变量作为值的符号名称。变量的名称,称为标识符,符合一定的规则。

JavaScript 标识符必须以字母、下划线 (_) 或美元符号 ($) 开头;后续字符也可以是数字 (0-9)。因为 JavaScript 区分大小写,所以字母包括字符“A”到“Z”(大写)和字符“a”到“z”(小写)。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types

let overusedWords[j] = overusedWords[j] + 1;

您可以更改overusedWords[j] = overusedWords[j] + 1;为 j 索引处的更新数组overusedWords

同样在您的代码中应该只检查i < newStory.length而不是检查i <= newStory.length,这是一种用于循环数组的模式,防止索引越界。


推荐阅读