简体   繁体   English

布尔值取1/0以及true / false

[英]Boolean to take 1/0 as well as true/false

I'm using the following code. 我正在使用以下代码。 Is there a way I can re-write it so the Boolean (or any other method) will take 1 and 0 as well? 有没有一种方法可以重写它,以便布尔值(或任何其他方法)也取1和0? Right now it only takes true/false as values. 现在,它仅将true / false作为值。 Can I do this without checking for 1/0 and then turning that into true/false? 我可以在不检查1/0然后将其转换为true / false的情况下执行此操作吗? Eg give a true or false just by using 1/0 as values. 例如,仅使用1/0作为值即可给出对或错。

$("#toggle").toggles({
  drag: true,
  click: true,
  text: {
    on: "ON",
    off: "OFF"
  },
  on: Boolean($("#container").attr("data-active")),
  animate: 150,
  easing: "swing",
  checkbox: null,
  clicker: null,
  width: 80,
  height: 16,
  type: "compact"
});

You pretty much never need Boolean() in JavaScript. 您几乎从不需要JavaScript中的Boolean()

Simply use !!$("#container").attr("data-active") to convert the value to a boolean (negating a value converts it to boolean, negating it again undoes the negation) 只需使用!!$("#container").attr("data-active")将值转换为布尔值(取反,将其转换为布尔值,再次取反将取消取反)。

Also, I would rather use $("#container").data("active") - by using data() , jQuery automatically converts the strings true / false to a boolean. 另外,我宁愿使用$("#container").data("active") -通过使用data() ,jQuery自动将字符串true / false转换为布尔值。

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

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