gpt4 book ai didi

javascript - 为什么 Node 只是打印出文件中的内容?

转载 作者:行者123 更新时间:2023-11-30 11:10:06 26 4
gpt4 key购买 nike

我对 node.js 有疑问,我对它不是很熟悉。

我有一个 JavaScript 文件,我需要使用 .load "filename.js" 将该文件加载到 node.js。

当我运行命令时,我只打印了文件中的代码。

这是我要加载的文件的代码。我已经进行了向我建议的更改。但我仍然从代码中得到完整的打印结果。

class ArithmeticTaskRunner 
{
constructor()
{
this.tasks = [];
}
addNegationTask()
{
const negationTask = (x) => -x;
this.tasks.push(negationTask)
return this;
}
addAdditionTask(y)
{
const additionByY = (x) => x + y;
this.tasks.push(additionByY)
return this;
}
addMultiplicationTask(y)
{
const multiplyByY = (x) => x * y;
this.tasks.push(multiplyByY)
return this;
}
taskCount()
{
return this.tasks.length;
}
execute(n)
{
let currentResult = n;
for(let task of this.tasks)
{
currentResult = task(currentResult)
}
return currentResult;
}
}
let taskRunner = new ArithmeticTaskRunner()
taskRunner.addAdditionTask(10)
taskRunner.addNegationTask()
taskRunner.addMultiplicationTask()
taskRunner.execute(2)

这里是这个任务需要的输出和输入的例子

1.

let taskRunner = new ArithmeticTaskRunner() undefined taskRunner.addAdditionTask(2) undefined taskRunner.addMultiplicationTask(4) undefined taskRunner.addAdditionTask(10) undefined taskRunner.execute(2) 26 taskRunner.execute(-2) 10

2.

taskRunner.execute() -5 taskRunner.execute(10) -10 taskRunner.taskCount 3

最佳答案

如果你想有一个 REPL session 并在命令行中运行命令,你可以使用 repl 模块。

const repl = require('repl');

class ArithmeticTaskRunner {
... // Your class definition
}

// This starts the REPL session with the ArithmeticTaskRunner defined
repl.start().context.ArithmeticTaskRunner = ArithmeticTaskRunner;

然后在终端:

node filename.js

当你有 Node 运行时:

let taskRunner = new ArithmeticTaskRunner()
taskRunner.addAdditionTask(2)
taskRunner.addMultiplicationTask(4)
taskRunner.addAdditionTask(10)
taskRunner.execute(2)
taskRunner.execute(-2)

如果要完整运行代码并输出结果,请在代码中使用console.log 并运行node filename.js:

class ArithmeticTaskRunner {
... // Your class definition
}

let taskRunner = new ArithmeticTaskRunner()
taskRunner.addAdditionTask(2)
taskRunner.addMultiplicationTask(4)
taskRunner.addAdditionTask(10)

console.log(taskRunner.execute(2))
console.log(taskRunner.execute(-2))

在终端中:

node filename.js

关于javascript - 为什么 Node 只是打印出文件中的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54053350/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com