Javascript中最后一次求值的表达式

Last evaluated expression in Javascript

本文关键字:表达式 最后一次 Javascript      更新时间:2023-09-26

是否有可能在Javascript中获得最后评估表达式的结果?例如:

var a = 3;
var b = 5;
a * b;
console.log(lastEvaluatedExpression); // should print 15

它会像eval()一样返回最后求值的表达式,但是我不能使用eval()

在JavaScript中没有标准的、具体化的"最后求值表达式的结果"的概念。实际上并没有太多的语言有这样的东西。各种JavaScript repl可能会提供一些类似的功能,但这是特定于这些repl的。

——package。json -

  "dependencies": {
    "stream-buffers": "^3.0.1"
  },

——main.js——

const streamBuffers = require('stream-buffers');
const repl = require('repl');
const reader = new streamBuffers.ReadableStreamBuffer();
const writer = new streamBuffers.WritableStreamBuffer();
const r = repl.start({
    input: reader, 
    output: writer,
    writer: function (output) {
        console.log(output)
        return output;
    }
});
reader.push(`
var a = 3;
var b = 5;
a * b;`);
reader.stop();

——output——

undefined
undefined
15

见:https://nodejs.org/api/repl.html

这在javascript中不可能。目前我能想到的唯一方法(不需要编写新的解释器)就是使用Coffeescript。Coffeescript自动返回最后一个表达式。

http://coffeescript.org/

http://coffeescript.org/extras/coffee-script.js

包括Coffeescript.compileCoffeescript.eval等功能

对于最后求值的表达式没有标准调用。不,你需要存储值。例如,你可以这样做:

var a = 3;
var b = 5;
var c = a * b;
var consoleResult = c.toString();
console.log(consoleResult); // should print 15
   //Then make your program logic change the value of consoleResult, as needed.