JavaScript强制转换/更改为布尔值

时间:2018-09-13 05:20:35

标签: javascript

如何将以下代码转换/更改为布尔值:

var $templateContext = $(templateHTML);
var ePopup = $templateContext.data('e-popup');
if (typeof ePopup === 'undefined') {
   ePopup = 'yes';
} // If not set, give it the value of 'yes'.

那我该怎么做呢?

if (ePopup === 'no' || ePopup === 'false' || !ePopup) {
    okayToLaunchPopup = false;
}

这是布尔值吗?

if (typeof ePopup === 'undefined') {
   ePopup = 'yes';
}

谢谢

3 个答案:

答案 0 :(得分:0)

让我们看看这是否对您有帮助。

okayToLaunchPopup = ePopup = typeof ePopup === 'undefined' ? true: false;

答案 1 :(得分:0)

这可以简单地完成。仅当epopup具有任何特定值时才执行,如果value为null或未定义则将不执行。

if (typeof ePopup) {  
   ePopup = 'yes';
}

也和其他人一样。

答案 2 :(得分:0)

在javascript中将事物强制转换为布尔值的最简单方法是使用!! (不是这样的)。例如:

const myString ='某些单词'; console.log(!! myString)// true;

const emptyString =''; console.log(!! myString)//否;