`
Odysseus_110
  • 浏览: 120606 次
  • 性别: 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; }

分享到:
评论

相关推荐

    Curve Shapes: Comparison and Alignment

    曲线形状:比较与对齐 在这篇文献中,作者John C. Femiani、Anshuman Razdan以及Gerald Farin提出了一个针对可微分两次的曲线进行部分匹配识别的方法。该方法在比较两条曲线上的点时采用等弧长间隔对应,并使用曲率...

    java中排序报:Comparison method violates its general contract异常的解决

    在Java编程中,当执行排序操作时,可能会遇到一个特定的异常:“Comparison method violates its general contract”。这个异常通常发生在使用`Arrays.sort()`或`Collections.sort()`方法时,尤其是在从Java 6升级到...

    LabVIEW学习笔记 LabVIEW学习笔记

    ### LabVIEW学习笔记知识点梳理 #### 一、调试技巧与数据监测 - **探针工具**: 在调试过程中,可以通过右键菜单中的`probe`和`custom probe`功能来设置探针,用于实时监测数据流。这有助于理解数据如何在各个节点...

    javascript 试题及答案

    本文将对JavaScript试题及答案进行解读,涵盖了JavaScript基础知识、语法格式、变量声明、运算符、_comparison operators、逻辑运算符、赋值语句等多方面的知识点。 JavaScript基础知识 1. JavaScript技术特征:...

    Expatriate management: Comparison of MNCs across four parent countries

    Expatriate management: Comparison of MNCs across four parent countries A 145 Expatriate Management: Comparison of MNCs Across Four Parent Countries Richard B. Peterson ! Nancy K. Napier ! Won Shul...

    jsgrids:comparison比较工具,用于比较JavaScript数据网格和电子表格库

    我建立了许多用于数据审核和工作流的内部工具,每隔几个月我就为JavaScript寻找最佳的数据网格或类似电子表格的库。 其他列表和站点已过时且未维护。 我的目标是让为顶部JavaScript前端框架(所有数据网格和电子表格...

    A Smarter Way to Learn JavaScript.pdf

    在此基础上,进一步学习了比较运算符(Comparison operators),if-else和else if语句(if else and elseif statements),以及如何测试一组条件(Testing sets of conditions)。 数组是编程中常用的数据结构,...

    Linux assemblers: A comparison of GAS and NASM

    Linux assemblers: A comparison of GAS and NASM A side-by-side look at GNU Assembler (GAS) and Netwide Assembler (NASM).

    JavaScript Tutorial.docx

    - 比较运算符(Comparison Operators):例如 `==`,`!=`,`&gt;`,`等用于比较操作。 - 阿拉伯运算符(Selected Arithmetic Operators):例如 `+`,`-`,`*`,`/`,`%` 用于数学计算。 - 逻辑运算符(Logical ...

    Oracle Solaris 8 PCI:SBus Comparison-20

    此文档"PCI:SBus Comparison"是Oracle Solaris 8中关于PCI(Peripheral Component Interconnect)总线与SBus(Sun Bus)总线之间比较的技术指南。这份文档的目的是帮助系统管理员和硬件工程师理解这两种总线架构的...

    GAN学习笔记

    ### GAN学习笔记知识点梳理 #### 一、生成与判别式模型的比较 - **标题**: On Discriminative vs. Generative Classifiers: A Comparison of Logistic Regression and Naive Bayes - **主要内容**: - 介绍了生成式...

    JavaScript+js语法基础+js数据类型+js数据类型转换+js运算符

    - 比较运算符(Comparison Operators):如`==`, `===`, `, `&gt;`, `, `&gt;=`,用于比较值。 - 逻辑运算符(Logical Operators):如`&&`, `||`, `!`,处理布尔值。 - 三元运算符(Conditional Operator):`condition ?...

    comparison of db2 vs oracle

    ### DB2与Oracle数据库对比分析 #### 引言:为何选择IBM DB2? 随着全球数字化进程的加速,企业面临着前所未有的数据处理挑战。为了更好地利用信息技术(IT),许多组织正在寻求更智能、更高效的解决方案来应对日益...

    Javascript-Guidelines:Javascript 基础和指南

    Javascript 基础和指南 编写 javascript 时遵循的简单方法 目录 [评论] (#comments) [类型(原语)] (#datatypes) [数组] (#arrays) [对象] (#objects) [字符串] (#strings) [功能] (#functions) [变量] (#...

    JavaScript in 10 Minutes

    2. **Lazy Scoping**: Refers to the way variables are scoped in JavaScript. Variables declared within a function are accessible throughout the function body, regardless of where they are defined. This ...

Global site tag (gtag.js) - Google Analytics