英文:
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 = 'false';
val = {'true': true, 'false': 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('true'), typeof bOrS('true'));
console.log(bOrS('false'), typeof bOrS('false'));
console.log(bOrS('foo'), typeof bOrS('foo'));
<!-- end snippet -->
答案4
得分: 0
你可以只用 &&
和 ||
来实现它:
value = val == "true" || val != "false" && val;
但在一个月或两个月后,你还能理解它吗?
const toBool = val => val == "true" || val != "false" && val;
["true", "false", "something", ""].forEach(val => {
const value = toBool(val);
console.log({ val, value, type: typeof value });
});
英文:
You can do it with just a &&
and a ||
:
value = val == "true" || val != "false" && 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 => val == "true" || val != "false" && val;
["true", "false", "something", ""].forEach(val => {
const value = toBool(val);
console.log({ val, value, type: typeof value });
});
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论