`
Odysseus_110
  • 浏览: 117039 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

javascript 权威指南 学习笔记2: Comparison Operators

阅读更多

 

Comparison Operators

The most commonly used types of relational operators are the comparison operators, which are used to determine the relative order of two values. The comparison operators are:

Less than (< )

The < operator evaluates to true if its first operand is less than its second operand; otherwise it evaluates to false .

Greater than (> )

The > operator evaluates to true if its first operand is greater than its second operand; otherwise it evaluates to false .

Less than or equal (<= )

The <= operator evaluates to true if its first operand is less than or equal to its second operand; otherwise it evaluates to false .

Greater than or equal (>= )

The >= operator evaluates to true if its first operand is greater than or equal to its second operand; otherwise it evaluates to false .

The operands of these comparison operators may be of any type. Comparison can be performed only on numbers and strings, however, so operands that are not numbers or strings are converted. Comparison and conversion occur as follows:

  • If both operands are numbers, or if both convert to numbers, they are compared numerically.

  • If both operands are strings or convert to strings, they are compared as strings.

  • If one operand is or converts to a string and one is or converts to a number, the operator attempts to convert the string to a number and perform a numerical comparison. If the string does not represent a number, it converts to NaN , and the comparison is false . (In JavaScript 1.1, the string-to-number conversion causes an error instead of yielding NaN .)

  • If an object can be converted to either a number or a string, JavaScript performs the numerical conversion. This means, for example, that Date objects are compared numerically, and it is meaningful to compare two dates to see whether one is earlier than the other.

  • If the operands of the comparison operators cannot both be successfully converted to numbers or to strings, these operators always return false .

  • If either operand is or converts to NaN , the comparison operator always yields false .

Keep in mind that string comparison is done on a strict character-by-character basis, using the numerical value of each character from the Unicode encoding. Although in some cases the Unicode standard allows equivalent strings to be encoded using different sequences of characters, the JavaScript comparison operators do not detect these encoding differences; they assume that all strings are expressed in normalized form. Note in particular that string comparison is case-sensitive, and in the Unicode encoding (at least for the ASCII subset), all capital letters are "less than" all lowercase letters. This rule can cause confusing results if you do not expect it. For example, according to the < operator, the string "Zoo" is less than the string "aardvark".

 


Note that you can convert any value x to a boolean value by applying this operator twice: !!x .

 

Because of the way signed integers are represented in JavaScript, applying the ~ operator to a value is equivalent to changing its sign and subtracting 1. For example ~0x0f evaluates to 0xfffffff0 , or -16.

 

 

 

delete is a unary operator that attempts to delete the object property, array element, or variable specified as its operand.[3] It returns true if the deletion was successful, and false if the operand could not be deleted. Not all variables and properties can be deleted: some built-in core and client-side properties are immune from deletion, and user-defined variables declared with the var statement cannot be deleted.

 

 

 

 

var o = {x:1, y:2};  // Define a variable; initialize it to an object

delete o.x;          // Delete one of the object properties; returns true

typeof o.x;          // Property does not exist; returns "undefined"

delete o.x;          // Delete a nonexistent property; returns true

delete o;            // Can't delete a declared variable; returns false

delete 1;            // Can't delete an integer; returns true

x = 1;               // Implicitly declare a variable without var keyword

delete x;            // Can delete this kind of variable; returns true

x;                   // Runtime error: x is not defined

Note that a deleted property, variable, or array element is not merely set to the undefined value. When a property is deleted, the property ceases to exist. See the related discussion in Section 4.3.2 .

delete is standardized by the ECMAScript v1 specification and implemented in JavaScript 1.2 and later. Note that the delete operator exists in JavaScript 1.0 and 1.1 but does not actually perform deletion in those versions of the language. Instead, it merely sets the specified property, variable, or array element to null .

It is important to understand that delete affects only properties, not objects referred to by those properties. Consider the following code:

 

 

var my = new Object(  );    // Create an object named "my"

my.hire = new Date(  );     // my.hire refers to a Date object

my.fire = my.hire;          // my.fire refers to the same object

delete my.hire;             // hire property is deleted; returns true

document.write(my.fire);    // But my.fire still refers to the Date object 

 

5.10.7 Array and Object Access Operators

As noted briefly in Chapter 3 , you can access elements of an array using square brackets ([] ), and you can access elements of an object using a dot (. ). Both [] and . are treated as operators in JavaScript.

The . operator expects an object as its left operand and an identifier (a property name) as its right operand. The right operand should not be a string or a variable that contains a string; it should be the literal name of the property or method, without quotes of any kind. Here are some examples:

document.lastModified

navigator.appName

frames[0].length

document.write("hello world") 

If the specified property does not exist in the object, JavaScript does not issue an error, but instead simply returns undefined as the value of the expression.

Most operators allow arbitrary expressions for either operand, as long as the type of the operand is suitable. The . operator is an exception: the righthand operand must be an identifier. Nothing else is allowed.

The [] operator allows access to array elements. It also allows access to object properties without the restrictions that the . operator places on the righthand operand. If the first operand (which goes before the left bracket) refers to an array, the second operand (which goes between the brackets) should be an expression that evaluates to an integer. For example:

frames[1]

document.forms[i + j]

document.forms[i].elements[j++] 

If the first operand to the [] operator is a reference to an object, the second operand should be an expression that evaluates to a string that names a property of the object. Note that in this case, the second operand is a string, not an identifier. It should be a constant in quotes or a variable or expression that refers to a string. For example:

document["lastModified"]

frames[0]['length']

data["val" + i] 

The [] operator is typically used to access the elements of an array. It is less convenient than the . operator for accessing properties of an object because of the need to quote the name of the property. When an object is used as an associative array, however, and the property names are dynamically generated, the . operator cannot be used; only the [] operator will do. This is commonly the case when you use the for/in loop, which is introduced in Chapter 6 . For example, the following JavaScript code uses a for/in loop and the [] operator to print out the names and values of all of the properties in an object o :

for (f in o) {

    document.write('o.' + f + ' = ' + o[f]);

    document.write('<br>');

} 

 

a[0] = function(x) { return x*x; };  // Define a function and store it

a.sort(function(a,b){return a-b;});  // Define a function; pass it to another

var tensquared = (function(x) {return x*x;})(10);  // Define and invoke

 

So, an object of class Complex inherits properties from the Complex.prototype object, which itself inherits properties from Object.prototype . Thus, the Complex object inherits properties of both objects. When you look up a property in a Complex object, the object itself is searched first. If the property is not found, the Complex.prototype object is searched next. Finally, if the property is not found in that object, the Object.prototype object is searched.

 

Since JavaScript is a loosely typed language, this rule does not apply -- a program can create any number of properties in any object.

 

Truncating an array by setting its length property is the only way that you can actually shorten an array. If you use the delete operator to delete an array element, that element becomes undefined, but the length property does not change.

 

 

For example, the function specified by a function literal expression can be stored into a variable, passed to another function, or even invoked directly:

a[0] = function(x) { return x*x; };  // Define a function and store it

a.sort(function(a,b){return a-b;});  // Define a function; pass it to another

var tensquared = (function(x) {return x*x;})(10);  // Define and invoke

 

There are a few other tricks that can be useful for performing explicit conversions. To convert a value to a string, concatenate it with the empty string:

var x_as_string = x + ""; 

To force a value to a number, subtract zero from it:

var x_as_number = x - 0; 

And to force a value to boolean, use the ! operator twice:

var x_as_boolean = !!x;

Because of JavaScript's tendency to automatically convert data to whatever type is required, explicit conversions are usually unnecessary. They are occasionally helpful, however, and can also be used to make your code clearer and more precise.

 

var string_value = String(number);  // Use the String(  ) constructor as a function

var string_value = number + "";    // Concatenate with the empty string

Another technique for converting numbers to strings is with the toString( ) method:

string_value = number.toString(  ); 
var n = 17;

binary_string = n.toString(2);        // Evaluates to "10001"

octal_string = "0" + n.toString(8);   // Evaluates to "021"

hex_string = "0x" + n.toString(16);   // Evaluates to "0x11"

Converting Strings to Numbers

var number = Number(string_value);

var number = string_value - 0;
parseInt("3 blind mice");    // Returns 3

parseFloat("3.14 meters");   // Returns 3.14

parseInt("12.34");           // Returns 12

parseInt("0xFF");            // Returns 255 

parseInt( ) can even take a second argument specifying the radix (base) of the number to be parsed. Legal values are between 2 and 36. For example:

parseInt("11", 2);           // Returns 3 (1*2 + 1)

parseInt("ff", 16);          // Returns 255 (15*16 + 15)

parseInt("zz", 36);          // Returns 1295 (35*36 + 35)

parseInt("077", 8);          // Returns 63 (7*8 + 7)

parseInt("077", 10);         // Returns 77 (7*10 + 7) 

If parseInt( ) or parseFloat( ) cannot convert the specified string to a number, it returns NaN :

parseInt("eleven");          // Returns NaN

parseFloat("$72.47");        // Returns NaN

 

 

 

 

 

span.meecallWrapper { font-size:1em; color:#B0E0E6; text-decoration:none; } a.meecallLink { color:#000000; text-decoration:none; } span.meecallInLink:hover { background-color:#B0E0E6; }

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics