admin管理员组文章数量:1291455
In Swift, I can do this to define a variable:
let foo: String = {
if bar {
return "42"
} else {
return "43"
}
}()
How can I define a variable like this in JavaScript? I know that you can define a variable as undefined and redefine it in the if block, but that's an ugly syntax IMO, since "foo" would get repeated 3 times instead of 1 in the Swift example:
let foo
if (bar) {
foo = "42"
} else {
foo = "43"
}
In Swift, I can do this to define a variable:
let foo: String = {
if bar {
return "42"
} else {
return "43"
}
}()
How can I define a variable like this in JavaScript? I know that you can define a variable as undefined and redefine it in the if block, but that's an ugly syntax IMO, since "foo" would get repeated 3 times instead of 1 in the Swift example:
let foo
if (bar) {
foo = "42"
} else {
foo = "43"
}
Share
edited Oct 14, 2022 at 16:04
Joakim Danielson
52.1k5 gold badges33 silver badges71 bronze badges
asked Oct 14, 2022 at 15:26
glyvoxglyvox
58.1k29 gold badges185 silver badges238 bronze badges
5 Answers
Reset to default 14If the logic is short enough you could use a conditional operator:
let foo = bar ? "42" : "43"
If the logic is more plicated, then i personally would do the last example you showed. But one other alternative you could consider is using an immediately invoked function expression:
let foo = (() => {
if (bar) {
return "42"
} else {
return "43"
}
})()
This creates an anonymous function, calls it immediately, and then whatever it returns gets assigned to foo
.
If you're just setting the value conditionally you can use a ternary expression:
const foo = bar ? '42' : '43'
You could use a function for more plex logic:
let bar = true;
const foo = puteFoo(bar);
function puteFoo(bar) {
if (bar) {
return "42";
}
return "43";
}
console.log(foo); // 42
Or an IIFE:
let bar = true;
const foo = (() => {
if (bar) {
return "42";
}
return "43";
})()
console.log(foo); // 42
You can use ternary operator:
let variable = true ? "A" : "B"
In you case:
let foo = bar ? '42' : '43'
Just to add a frisson to the answer set:
const bar = false
let foo = (() => {
switch(true) {
case bar:
return "42"
default:
return "43"
}
})()
console.log(foo) // 43
let foo = bar ? '42' : '43'
condition ? exprIfTrue : exprIfFalse
本文标签: Define a variable in JavaScript as a blockStack Overflow
版权声明:本文标题:Define a variable in JavaScript as a block - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741534610a2383955.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论