简体   繁体   English

console.log在求值之前/不求值时的表达式

[英]console.log an expression before/without evaluation

Given a statement such as let boolVal = 1 < 2 , is there a way to console log the actual expression, ie 1 < 2 not the true result? 给定一条语句,例如let boolVal = 1 < 2 ,有没有办法控制台记录实际表达式,即1 < 2 不是 true结果?

 let boolVal = 1 < 2; console.log(boolVal) // logs out the boolean result console.log(boolVal.toString()) // logs out the boolean result as a string /* is there a way to get just '1 < 2' itself to be logged out? */ 

You can achieve this by making a custom function: 您可以通过创建自定义函数来实现此目的:

 function printExpression(x,y){ console.log( (x<y?x:y) + " < " + (x<y?y:x)); } printExpression(1,2); printExpression(4,3); 

You could make a function that makes the comparison, and log both the result of that function and the function itself. 您可以创建一个进行比较的函数,并记录该函数的结果和函数本身。

 function boolValComparer(val1, val2) { console.log(val1, '<', val2); // logs the boolean comparison as string with parameters return val1 < val2; } let boolVal = boolValComparer(1, 2); console.log(boolVal) // logs out the boolean result console.log(boolValComparer) // logs out the comparer function as a string 

let boolVal = 1 < 2;

You cant log 1 < 2 directly because they are compared and stored in boolVal. 您不能直接记录1 <2 ,因为它们已比较并存储在boolVal中。 What you can do is a workaround. 您可以做的是一种解决方法。

Store 1 and 2 in variables var1 and var2. 12存储在变量var1和var2中。

let boolVal = var1 < var2

if boolVal:
    console.log(var1 + "<" + var2)
else:
    console.log(var1 + ">" + var2)

From your response in the comment section, I see you need a generic solution with different operands. 从评论部分的答复中,我看到您需要一个具有不同操作数的通用解决方案。 The simplest solution I can think of is by using eval. 我能想到的最简单的解决方案是使用eval。

1- Create an array of strings array[]. 1-创建一个字符串数组array []。 You could creare a string. 您可以创建一个字符串。 "" +expression. “” +表达式。 2- console.log(array[index]+ eval(array[index]) ) 2- console.log(array [index] + eval(array [index]))

Although i would not recommend. 虽然我不建议。 Eval is bad for both performance and security. 评估对性能和安全性都不利。 Another workaround is to make a connection for the results and for string you create from the first step. 另一个解决方法是为您从第一步创建的结果和字符串建立连接。 Like 2 arrays or create objects with 2 attributes. 喜欢2个数组或创建具有2个属性的对象。 {value:, expression}. {value :, expression}。 You can print them accourdingly when you print the variable. 当您打印变量时,可以按照喜好方式打印它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM