javascript - 我们如何在 file.txt 中找到没有 HTML 的 JavaScript 中的单词?

标签 javascript html

在我的项目中,我试图在一个文件中找到一些单词,我用 JS 编写程序,但我有一些语法问题,我不知道为什么。目标是当程序找到“rose”时,它会在终端“flower”等上写入。 我的程序是:

var fs = require('fs');
var str = fs.readFileSync('input.txt', 'utf8');

str.split(/\s+/).forEach(s =>
  console.log(
    s === 'rose'
      ? 'flower'
      : s === 'bird'
      ? 'animal'
      : s === 'cookie'
      ? 'dog'
      : 'unknown'
  )
);

终端上出现的不同错误是:

  js: "prog.js", line 5: syntax error
js: str.split(/\s+/).forEach(s =>
js: ............................^
js: "prog.js", line 6: syntax error
js:   console.log(
js: ..........^
js: "prog.js", line 7: syntax error
js:     s === 'rose'
js: ........^
js: "prog.js", line 9: syntax error
js:       : s === 'bird'
js: .......^
js: "prog.js", line 11: syntax error
js:       : s === 'cookie'
js: .......^
js: "prog.js", line 13: syntax error
js:       : 'unknown'
js: .......^
js: "prog.js", line 15: syntax error
js: );
js: ^
js: "prog.js", line 1: Compilation produced 7 syntax errors.

为了运行程序,我使用了这个命令:rhino prog.js

那你能帮我找出错误吗?

最佳答案

你收到错误是因为 Rhino 当前不支持箭头函数:即 () => { ...}

参见:https://mozilla.github.io/rhino/compat/engines.html#ES2015-syntax-destructuring--parameters-defaults--arrow-function

您很幸运,这很容易解决!只需删除箭头功能;这应该有效:

var fs = require('fs');
var str = fs.readFileSync('input.txt', 'utf8');

str.split(/\s+/).forEach(function (s) {
  return console.log(s === 'rose' ? 'flower' : s === 'bird' ? 'animal' : s === 
'cookie' ? 'dog' : 'unknown');
});

关于javascript - 我们如何在 file.txt 中找到没有 HTML 的 JavaScript 中的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52704498/

相关文章:

javascript - NodeJS - 目录结构模式

javascript - Rails/Ajax 不替换 DIV,而是将新的 DIV 嵌套在旧的 DIV 中

html - 站点最小高度 100%

javascript - 检查对象数据

javascript - 在 JavaScript 中调用不带参数的 concat 有什么作用

javascript - JQuery 在链接的静态页面中搜索,并在不破坏列表的情况下突出显示找到的单词

html - Adsense 自动广告 CLS 问题

java - 从资源管理器调用 war 文件中的 HTML 页面

html - 如何在没有 HTML 标记的情况下向屏幕阅读器隐藏 CSS 生成的内容?

javascript - 需要有关随机图像旋转的指南吗?