javascript - 为什么这不可能: 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;
};
};
};
解决方案
您不能创建名称包含 [ 字符的变量
您在应用程序中使用变量作为值的符号名称。变量的名称,称为标识符,符合一定的规则。
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
,这是一种用于循环数组的模式,防止索引越界。
推荐阅读
- python - 使用 enumerate 计算一个值在 np 数组中的位置
- php - PHP session_start 返回 false,$_SESSION 变量不是持久的
- git - 为什么我的 git diff 在@@ 之后显示评论
- python - 在 django 中为用户创建公共配置文件
- python - 反向波兰符号算法不能与相同的操作数正确工作
- html - WKWebView 画布问题。画布内的链接没有做任何事情
- ruby-on-rails - 如何修复 RVM gemsets 中的 [missing bin/ruby] 列表
- python - 如何从 Win-R 窗口更改目录?
- php - PHP、Angular、HTACCESS - 只允许来自源域的请求
- swift - NavigationBarTitle 自动显示模式不起作用