作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我主要是一名 JavaScript 开发人员,但目前正在处理一些 Groovy 代码,并且无法弄清楚如何在 JavaScript 中完成一些 super 简单的事情。
下面是我正在尝试执行的等效 JavaScript。
我特别想找出 Java(或 Groovy)等同于在 JS(Java 中的映射)中创建一个对象仅使用现有变量名,例如{a, b, c}
下面代码片段中的简写。任何指导将不胜感激!
javaScriptExample()
function javaScriptExample () {
// the variables already exist in the program that I'm working in
const a = 'a'
const b = 'bee'
const c = 'see'
// ➡️ Here's where I'm stuck. ⬅️
// I simply want to be able to arbitrarily pass variable keys and values
// as a map to another function, _using just the variable keys_,
// e.g. the equivalent of JavaScript's `{a, b, c}` in the next call
doOtherStuffWithVariables({a, b, c})
}
function doOtherStuffWithVariables (obj) {
for (const key in obj) {
console.log(`variable ${key} has a value of "${obj[key]}" and string length of ${obj[key].length}`)
}
}
最佳答案
如前所述,Groovy 中没有捷径。但是如果你想要/需要这个语法,您可以使用 GroovyMacros 实现此目的.
例如一个非常直接的尝试:
@Macro
static Expression map(MacroContext ctx, final Expression... exps) {
return new MapExpression(
exps.collect{
new MapEntryExpression(GeneralUtils.constX(it.getText()), it)
}
)
}
用法:
def a = 42
def b = 666
println(map(a,b))
// → [a:42, b:666]
关于java - 从现有变量创建映射(例如,相当于 JavaScript 的 `{varA, varB, varC}` 的 Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65906680/
我主要是一名 JavaScript 开发人员,但目前正在处理一些 Groovy 代码,并且无法弄清楚如何在 JavaScript 中完成一些 super 简单的事情。 下面是我正在尝试执行的等效 Ja
我是一名优秀的程序员,十分优秀!