将其转换为布尔值如果是”false”或”true”,否则保留字符串。

huangapple go评论72阅读模式
英文:

convert to bool if "false" or "true", leave string otherwise

问题

val 是字符串的话,最高效的一行代码(如果可能的话)是:

value = (val == "true") ? true : ((val == "false") ? false : val);
英文:

What is the most efficient one-liner (if possible) for:

if (val == "true"){
 value = true;
}
else if (val == "false"){
 value = false;
}
else {
 value = val;
}

val is string.

答案1

得分: 1

value = val == "true" ? true : (val == "false" ? false : val);

英文:

Do it in one line with ternary operator :

value = val == "true" ? true : (val == "false" ? false : val);

答案2

得分: 0

let val = 'false';

val = {'true': true, 'false': false, [val]:val}[val]

console.log(val)
英文:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let val = &#39;false&#39;;

val = {&#39;true&#39;: true, &#39;false&#39;: false, [val]:val}[val]

console.log(val)

<!-- end snippet -->

答案3

得分: 0

你可以使用 null 合并操作符来处理给定的字符串的情况。

const bOrS = v => ({ true: true, false: false }[v] ?? v);

console.log(bOrS('true'), typeof bOrS('true'));
console.log(bOrS('false'), typeof bOrS('false'));
console.log(bOrS('foo'), typeof bOrS('foo'));
英文:

You could take an object with null colalescing with the given string.

<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const
bOrS = v => ({ true: true, false: false }[v] ?? v);

console.log(bOrS(&#39;true&#39;), typeof bOrS(&#39;true&#39;));
console.log(bOrS(&#39;false&#39;), typeof bOrS(&#39;false&#39;));
console.log(bOrS(&#39;foo&#39;), typeof bOrS(&#39;foo&#39;));

<!-- end snippet -->

答案4

得分: 0

你可以只用 &amp;&amp;|| 来实现它:

value = val == &quot;true&quot; || val != &quot;false&quot; &amp;&amp; val;

但在一个月或两个月后,你还能理解它吗?

const toBool = val => val == &quot;true&quot; || val != &quot;false&quot; &amp;&amp; val;

["true", "false", "something", ""].forEach(val => {
  const value = toBool(val);
  console.log({ val, value, type: typeof value });
});
英文:

You can do it with just a &amp;&amp; and a ||:

value = val == &quot;true&quot; || val != &quot;false&quot; &amp;&amp; val;

but will you still understand it when you read it in a month or two?

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const toBool = val =&gt; val == &quot;true&quot; || val != &quot;false&quot; &amp;&amp; val;

[&quot;true&quot;, &quot;false&quot;, &quot;something&quot;, &quot;&quot;].forEach(val =&gt; {
  const value = toBool(val);
  console.log({ val, value, type: typeof value });
});

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年1月9日 19:10:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75056427.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定