Using the Boolean Object


Using the Boolean Object

You can create Boolean objects with the Boolean constructor, passing a value of true or false to initialize the object, like this:

 var boolean1 = new Boolean(true) 

You can then assign new true or false values to the Boolean object:

 var boolean1 = new Boolean(true)  boolean1 = false  

Here's an example. In this case, I'll create a new Boolean object and toggle it between true and false when the user clicks a button using the JavaScript not operator, ! (see Table 2.3 and the section "Logical Operators" in Chapter 2, "The JavaScript Language: Data, Operators, and Branching," for more on the ! operator), which flips the logical sense of its argument:

 var boolean1 = new Boolean(true)  function toggler()  {      document.form1.text1.value = "boolean1 = " + boolean1.valueOf()      boolean1 = !boolean1  } 

Here's what this code looks like in the full example:

(Listing 19-05.html on the web site)
 <HTML>      <HEAD>          <TITLE>               Toggling Boolean Values          </TITLE>          <SCRIPT LANGUAGE="JavaScript">              <!--  var boolean1 = new Boolean(true)   function toggler()   {   document.form1.text1.value = "boolean1 = " + boolean1.valueOf() boolean1 graphics/ccc.gif = !boolean1   }  // -->          </SCRIPT>      </HEAD>      <BODY>          <H1>Toggling Boolean Values</H1>          <FORM NAME="form1">              <INPUT TYPE="TEXT" NAME="text1">              <INPUT TYPE="BUTTON" ONCLICK="toggler()" VALUE="Click Me!">          </FORM>      </BODY>  </HTML> 

You can see the results in Figure 19.5, where the value of the Boolean variable flips logical sense from true to false and back again each time you click the button.

Figure 19.5. Toggling a Boolean object's logical value.

graphics/19fig05.gif



Inside Javascript
Inside JavaScript
ISBN: 0735712859
EAN: 2147483647
Year: 2005
Pages: 492
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net