简体   繁体   English

JavaScript 中是否有等效的 Python 自文档表达式?

[英]is there an equivalent of Python self-documenting expressions in JavaScript?

in Python 3.8 it is possible to use self-documenting expressions in f-strings like this:在 Python 3.8 中,可以在 f 字符串中使用自记录表达式,如下所示:

>>> variable=5
>>> print(f'{variable=}')
variable=5

is there an equivalent feature in JavaScript? JavaScript 中是否有等效的功能?

The only reasonable way to do something like this would be for properties of objects:执行此类操作的唯一合理方法是针对对象的属性:

 const logObj = (obj) => { for (const [key, val] of Object.entries(obj)) { console.log(key, val); } }; const obj = { foo: 'fooval', bar: 'barval', }; logObj(obj);

There's no good way to do this for standalone variables.对于独立变量,没有好的方法可以做到这一点。 But the execution logic of a script should not (and, indeed, almost always does not) depend on the names of the variables used in the script - that would break minification and would be confusing to other readers of the script.但是脚本的执行逻辑不应该(事实上,几乎总是不)依赖于脚本中使用的变量的名称——这会破坏缩小并会让脚本的其他读者感到困惑。 Even if it might be theoretically possible to do something like即使理论上有可能做类似的事情

logVar(someVar)

and have the string someVar be logged (such as by throwing an error and examining the source text), that would be an extraordinary strange thing to do.并记录字符串someVar (例如通过抛出错误并检查源文本),这将是一件非常奇怪的事情。

You can self-assign a variable into an object and stringify it:您可以将变量自分配给对象并将其字符串化:

 let variable = 5; console.log(JSON.stringify({variable}));

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

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