简体   繁体   English

使用Javascript中的三元运算符将字符串转换为布尔值?

[英]String to Boolean using ternary operator in Javascript?

I have a result coming from PHP side and json_encode send all the values as string (not as it's original type). 我有一个来自PHP方面的结果, json_encode将所有值发送为字符串(而不是它的原始类型)。 The string coming at quote_tax is a 1|0 and of course this is true|false for example: 来自quote_tax的字符串是1|0 ,当然这是true|false例如:

{
  "country_id": "3",
  "country_name": "Italy",
  "contract_tax": "1",
  "quote_tax": "0",
  "contract_inflation": "0",
  "quote_inflation": "0"
}

When I want to perform some operation based on such values and because they are coming as string I need to do something like this: 当我想基于这样的值执行某些操作时,因为它们以字符串形式出现,我需要做这样的事情:

 data.quote_tax == '1' 
                ? $('#contract_tax').val(1).attr('checked', 'checked') 
                : $('#contract_tax').val(0).removeAttr('checked');

I did know about .parseInt() to convert them into a integer but I believe then I would need to have the same comparison but this case comparing with INT : 我确实知道.parseInt()将它们转换为整数,但我相信我需要进行相同的比较,但这种情况与INT比较:

 data.quote_tax == 1 
                ? $('#contract_tax').val(1).attr('checked', 'checked') 
                : $('#contract_tax').val(0).removeAttr('checked');

I have tried this way: 我试过这种方式:

 Boolean(data.quote_tax) == true 
                ? $('#contract_tax').val(1).attr('checked', 'checked') 
                : $('#contract_tax').val(0).removeAttr('checked');

And it doesn't work since Boolean(data.quote_tax) always evaluate as true even if data.quote_tax = '0' . 并且它不起作用,因为即使data.quote_tax = '0' Boolean(data.quote_tax)总是评估为true

I have check this posts already but I couldn't found a proper solution: 我已经检查了这些帖子,但我找不到合适的解决方案:

Any ideas what's wrong here or how to do this? 任何想法在这里有什么问题或如何做到这一点?

Values in Javascript are either "truthy" or "falsy", meaning they'll be interpreted as true or false in a boolean context. Javascript中的值是“truthy”或“falsy”,这意味着它们将在布尔上下文中被解释为truefalse In the case of numbers, 0 is false and all others are true . 在数字的情况下, 0false ,其他都为true If you convert your value to a number, you don't have to perform any other conversion to treat it as a boolean. 如果将值转换为数字,则不必执行任何其他转换将其视为布尔值。

 var x = parseInt('1'); x ? console.log(true) : console.log(false); x = parseInt('0'); x ? console.log(true) : console.log(false); 

See here for more information. 浏览此处获取更多信息。

You can combine the operators - parse the string to a number, and then convert to Boolean: 您可以组合运算符 - 将字符串解析为数字,然后转换为布尔值:

 console.log(Boolean(parseInt('0', 10))); console.log(!!parseInt('0', 10)); console.log(!!+'0'); 

Your last approach fails because any non-empty string evaluates to true if converted to a boolean, including "0" . 您的上一个方法失败,因为如果转换为布尔值(包括"0" ,任何非空字符串的计算结果为true


The integer 0 evaluates to false, while non-zero integers evaluate to true . 整数0计算结果为false,而非零的整数计算结果为true For this reason, parseInt(data.quote_tax) == 1 would be equivalent to parseInt(data.quote_tax) in your case. 因此,在您的情况下, parseInt(data.quote_tax) == 1将等同于parseInt(data.quote_tax)


However, I would stick with the first approach in this situation: 但是,在这种情况下我会坚持第一种方法:

data.quote_tax == '1'

This requires no type conversions, the intent is immediately obvious and is also doesn't require the developer to know the things I listed above to be understood. 这不需要类型转换,意图很明显,并且也不需要开发人员知道我上面列出的内容需要理解。 Don't make your code more complicated than it has to be. 不要让你的代码比它更复杂。

You can do something like this: 你可以这样做:

!!parseInt('1'); //true
!!parseInt('0'); //false

Personally I always try and stay away from coercing types . 就个人而言,我总是试图远离胁迫类型 The problem is that if you do as others have suggested, if (x) this works great for 0 & 1 . 问题是,如果你像其他人建议的那样做, if (x)这适用于01 What if for some reason you get a "false" , 2 , null or undefined . 如果由于某种原因你得到"false"2nullundefined ,该怎么办? What would you want your code to do here? 你希望你的代码在这里做什么?

 undefined ? console.log(true) : console.log(false); null ? console.log(true) : console.log(false); NaN ? console.log(true) : console.log(false); 2 ? console.log(true) : console.log(false); "false" ? console.log(true) : console.log(false); "true" ? console.log(true) : console.log(false); 

If you use === (as opposed to == ) it prevents Javascript coercion . 如果你使用=== (而不是== )它会阻止Javascript强制 You can then test for the string value "1" 然后,您可以测试字符串值"1"

 "1" === "1" ? console.log(true) : console.log(false); 1 === "1" ? console.log(true) : console.log(false); undefined === "1" ? console.log(true) : console.log(false); null === "1" ? console.log(true) : console.log(false); NaN === "1" ? console.log(true) : console.log(false); 2 === "1" ? console.log(true) : console.log(false); "false" === "1" ? console.log(true) : console.log(false); "true" === "1" ? console.log(true) : console.log(false); 

It now works a lot more consistently. 它现在可以更加一致地工作。 May or may not be an issue in your case but I prefer this method for the just in case factor. 在你的情况下可能会或可能不是一个问题,但我更喜欢这种方法的公正因素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM