mozilla
您的搜索结果

    表达式和运算符

    本章描述了JavaScript的表达式和运算符,包括赋值,比较,数值计算,位运算,逻辑运算,字符串(运算)和特殊运算符。

    表达式

    表达式 是一组可以计算出一个数值的有效的代码的集合

    从概念上讲,有两种表达式: 它们是:把一个值赋值给一个变量和那些可以简单得到一个值的式子。比如,x=7 就是第一种。这个表达式用“=”运算符 把值7赋值给变量x。这个表达式自己的值等于7。而代码 3 + 4则是第二种表达式,这个表达式用“+”运算符把3和4相加却并没有将结果7赋值给一个变量。

    JavaScript 有如下类型的表达式:

    • 算术: 求值结果为数字, 例如 3.14159. (通常使用 算术运算符.)
    • 字符串: evaluates to a character string, 例如, "Fred" or "234". (通常使用 字符串运算符.)
    • 逻辑: 求值结果为true或false. (通常包含 逻辑运算符.)
    • 对象: 求值结果为对象. (到 特殊运算符 中查阅多种不同的求值结果为对象的表达式.)

    运算符

    JavaScript中的运算符有以下几种。本节将介绍这些运算符和运算符的优先级 

    JavaScript包含二元运算符   和一元运算符, 以及一个特殊的三元运算符:条件运算符。 二元运算符要求在运算符前后各有一个操作数,如下所示:

    操作数1运算符 操作数2
    

    例如, 3+4 、 x*y。

    一元运算符则只需要一个操作数,操作数可以在运算符的前面或后面:

    运算符 操作数
    

    或者

    操作数 运算符
    

    例如, x++  和 ++x。

    赋值运算符

    赋值运算符基于它的右操作数的值来为左操作数赋值. 最基本的赋值运算符是等号 (=), 它将右操作数的值赋给左操作数。就是说, x = y 将 y 的值赋给 x.

    其他的赋值运算符是下表所列出的运算的简写:

    表 3.1 赋值运算符
    简写运算符 含义
    x += y x = x + y
    x -= y x = x - y
    x *= y x = x * y
    x /= y x = x / y
    x %= y x = x % y
    x <<= y x = x << y
    x >>= y x = x >> y
    x >>>= y x = x >>> y
    x &= y x = x & y
    x ^= y x = x ^ y
    x |= y x = x | y

    比较运算符

    比较运算符比较它的操作数并基于比较值是否为真来返回一个逻辑值. 操作数可以是数字、字符串、逻辑值或者对象. 字符串的比较是基于标准字典序,使用字符的Unicode值. 大多数情况下,如果两个操作数不是同一种类型的,JavaScript会尝试将它们转换为适合比较的类型.通常,转换的最终结果是进行数值比较. 唯一的例外是===和!==, 他们执行的是严格的相等性比较而不会在进行判断之前进行操作数类型转换 . 下表基于这段示例代码详述了比较运算符:

    var var1 = 3, var2 = 4;
    
    表 3.2 比较运算符
    操作数 Description 返回true的例子
    相等 (==) Returns true if the operands are equal. 3 == var1

    "3" == var1

    3 == '3'
    不等 (!=) Returns true if the operands are not equal. var1 != 4
    var2 != "3"
    严格相等 (===) Returns true if the operands are equal and of the same type. 另见 Object.is 和 sameness in JS. 3 === var1
    严格不等 (!==) Returns true if the operands are not equal and/or not of the same type. var1 !== "3"
    3 !== '3'
    大于 (>) Returns true if the left operand is greater than the right operand. var2 > var1
    "12" > 2
    大于等于 (>=) Returns true if the left operand is greater than or equal to the right operand. var2 >= var1
    var1 >= 3
    小于 (<) Returns true if the left operand is less than the right operand. var1 < var2
    "12" < "2"
    小于等于 (<=) Returns true if the left operand is less than or equal to the right operand. var1 <= var2
    var2 <= 5

    算术运算符

    算术运算符使用数值(字面量或者变量)作为操作数并返回一个数值.标准的算术运算符就是加减乘除(+-*/).当操作数是浮点数时,这些运算符表现得跟它们在大多数编程语言中一样(特殊要注意的是,除零会产生Infinity(译者注:大多数编程语言除零会抛出异常))例如:

    console.log(1 / 2); /* prints 0.5 */
    console.log(1 / 2 == 1.0 / 2.0); /* also this is true */
    

    另外,JavaScript还提供了下表中的算术运算符.

    表 3.3 算术运算符
    Operator Description Example
    %
    (求余)
    二元运算符. 返回相除之后的余数. 13 % 5 返回 3.(译者注:原文的例子是12%5得2,这个例子实在是不好,12与5求余求模都得2)
    ++
    (自增)
    一元运算符. 将操作数的值加一. 如果放在操作数前面 (++x), 则返回加一后的值; 如果放在操作数后面 (x++), 则返回操作数原值,然后再将操作数加一.

    var x=3; console.log(++x); //输入4,x=4

    var y=3;console.log(y++);//输出3,x=4;

    --
    (自减)
    一元运算符. 将操作数的值减一. 前后缀两种用法的返回值类似自增运算符.

    var x=3; console.log(--x); //输入2,x=2

    var y=3;console.log(y--);//输出3,x=2;

    -
    (一元负值符)
    一元运算符,返回操作数的负值. var x=3; console.log(-x); //输入-2

    位运算符

    位运算符将它的操作数视为32位的二进制串(0和1组成)而非十进制八进制或十六进制数.例如:十进制数字9用二进制表示为1001,位运算符就是在这个二进制表示上执行运算,但是返回结果是标准的JavaScript数值.

    下表总结了 JavaScript的位运算符.

    表 3.4 位运算符
    Operator Usage Description
    二进制与 AND a & b Returns a one in each bit position for which the corresponding bits of both operands are ones.
    二进制或 OR a | b Returns a one in each bit position for which the corresponding bits of either or both operands are ones.
    二进制异或 XOR a ^ b Returns a one in each bit position for which the corresponding bits of either but not both operands are ones.
    二进制非 NOT ~ a Inverts the bits of its operand.
    左移位 a << b 将a的二进制串向左移动b位,右边移入0.
    Sign-propagating right shift a >> b Shifts a in binary representation b bits to the right, discarding bits shifted off.
    Zero-fill right shift a >>> b Shifts a in binary representation b bits to the right, discarding bits shifted off, and shifting in zeros from the left.

    位逻辑运算符

    概念上来讲, 位逻辑运算符工作流程如下:

    • 操作数被转换为32位整型,以位序列(0和1组成)表示.
    • 第一个操作数的每一位都与第二个操作数的对应位组对: 第一位对应第一位,第二位对应第二位,以此类推.
    • 运算符被应用到每一对"位"上, 最终的运算结果由每一对“位”的运算结果组合起来.

    例如,十进制数9的二进制表示是1001,十进制数15的二进制表示是1111.因此,当位运算符应用到这两个值时,结果如下:

    表 3.5 位运算符范例
    表达式 结果 二进制描述
    15 & 9 9 1111 & 1001 = 1001
    15 | 9 15 1111 | 1001 = 1111
    15 ^ 9 6 1111 ^ 1001 = 0110
    ~15 -16 ~00000000...00001111 = 11111111...11110000
    ~9 -10 ~00000000...00001001 = 11111111...11110110

    注意位运算符“非”将所有的32位取反,而值的最高位(最左边的一位)为1则表示负数(2-补码表示法).

    移位运算符

    移位运算符带两个操作数:第一个是待移位的数,第二个是指定第一个数要被移多少位的数. 移位的方向由运算符来控制.

    移位运算符列表如下.

    表 3.6 移位运算符
    运算符 描述 范例
    <<
    (左移位)
    将第一个操作数向左移动指定数量的位. 左边移出位被抛弃. 左边移出的几位被丢弃.右边多出的空位由0补齐 9<<2 yields 36, because 1001 shifted 2 bits to the left becomes 100100, which is 36.
    >>
    (带符号右移)
    将第一个操作数向右移动指定数量的位. 右边移出位被抛弃. 左边多出的空位由原值的最左边数字补齐. 9>>2 yields 2, because 1001 shifted 2 bits to the right becomes 10, which is 2. Likewise, -9>>2 yields -3, because the sign is preserved.
    >>>
    (补零右移)
    将第一个操作数向右移动指定数量的位. 右边移出位被抛弃. 左边多出的空位由0补齐. 19>>>2 yields 4, because 10011 shifted 2 bits to the right becomes 100, which is 4. For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result.

    逻辑运算符

    逻辑运算符常用于布尔(逻辑)值之间; 当操作数都是布尔值时,返回值也是布尔值。 不过实际上&&和||返回的是一个特定的操作数的值,所以当它用于非布尔值的时候,返回值就可能是非布尔值。 逻辑运算符的描述如下。

    表 3.6 逻辑运算符
    运算符 范例 描述
    && expr1 && expr2 (逻辑与) 如果expr1能被转换为false,那么返回expr1;否则,返回expr2。因此,&&用于布尔值时,当操作数都为true时返回true;否则返回false.
    || expr1 || expr2 (逻辑或) 如果expr1能被转换为true,那么返回expr1;否则,返回expr2。因此,||用于布尔值时,当任何一个操作数为true则返回true;如果操作数都是false则返回false。
    ! !expr (逻辑非) 如果操作数能够转换为true则返回false;否则返回true。

    能被转换为false的值有null, 0, 空字符串("")和undefined。

    下面是&&(逻辑与)操作符的示例。

    var a1 =  true && true;     // t && t returns true
    var a2 =  true && false;    // t && f returns false
    var a3 = false && true;     // f && t returns false
    var a4 = false && (3 == 4); // f && f returns false
    var a5 = "Cat" && "Dog";    // t && t returns Dog
    var a6 = false && "Cat";    // f && t returns false
    var a7 = "Cat" && false;    // t && f returns false
    

    下面是||(逻辑或)操作符的示例。

    var o1 =  true || true;     // t || t returns true
    var o2 = false || true;     // f || t returns true
    var o3 =  true || false;    // t || f returns true
    var o4 = false || (3 == 4); // f || f returns false
    var o5 = "Cat" || "Dog";    // t || t returns Cat
    var o6 = false || "Cat";    // f || t returns Cat
    var o7 = "Cat" || false;    // t || f returns Cat
    

    下面是!(逻辑非)操作符的示例。

    var n1 = !true;  // !t returns false
    var n2 = !false; // !f returns true
    var n3 = !"Cat"; // !t returns false
    

    短路求值

    As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:

    • false && anything is short-circuit evaluated to false.
    • true || anything is short-circuit evaluated to true.

    The rules of logic guarantee that these evaluations are always correct. Note that the anything part of the above expressions is not evaluated, so any side effects of doing so do not take effect.

    字符串运算符

    In addition to the comparison operators, which can be used on string values, the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings. For example, "my " + "string" returns the string "my string".

    The shorthand assignment operator += can also be used to concatenate strings. For example, if the variable mystring has the value "alpha", then the expression mystring += "bet" evaluates to "alphabet" and assigns this value to mystring.

    特殊运算符

    JavaScript有下列特殊运算符:

    条件运算符

    条件运算符是JavaScript中唯一需要三个操作数的运算符。运算的结果根据给定条件在两个值中取其一。语法为:

    condition ? val1 : val2
    

    如果condition为true,则结果取val1。否则为val2。你能够在任何允许使用标准运算符的地方使用条件运算符。

    例如,

    var status = (age >= 18) ? "adult" : "minor";
    

    当age大于等于18的时候,语句将“adult”赋值给status;否则将“minor”赋值给status。

    逗号操作符

    逗号操作符(,)对两个操作数进行求值并返回第二个操作数的值。它常常用在for循环中,在每次循环时对多个变量进行更新。

    For example, if a is a 2-dimensional array with 10 elements on a side, the following code uses the comma operator to increment two variables at once. The code prints the values of the diagonal elements in the array:

    for (var i = 0, j = 9; i <= 9; i++, j--)
      document.writeln("a[" + i + "][" + j + "]= " + a[i][j]);
    

    delete

    delete 操作,删除一个对象或者一个对象的属性, 或者一个数组中某一个键值. 语法如下:

    delete objectName;
    delete objectName.property;
    delete objectName[index];
    delete property; // legal only within a with statement
    

    objectName是一个对象名, property 是一个已经存在的属性, index是数组中的一个已经存在的键值的索引值.

    第四行的形式只在一个声明的状态下是合法的, 从对象中删除一个属性。

    你能使用 delete 删除各种各样的隐式声明, 但是被var声明的除外 .

    如果 delete 操作成功, 属性或者元素会变成 undefined. 如果 delete可行会返回true,如果不成功返回false.

    x = 42;
    var y = 43;
    myobj = new Number();
    myobj.h = 4;    // create property h
    delete x;       // returns true (can delete if declared implicitly)
    delete y;       // returns false (cannot delete if declared with var)
    delete Math.PI; // returns false (cannot delete predefined properties)
    delete myobj.h; // returns true (can delete user-defined properties)
    delete myobj;   // returns true (can delete if declared implicitly)
    
    删除数组元素

    删除数组中的元素时,数组的长度是不变的,例如delete a[3], a[4]  ,a[4] 和a[3] 仍然存在变成了undefined.

    delete 删除数组中的一个元素, 这个元素就不在数组中了. 例如, trees[3]被删除,trees[3] 仍然可寻址并返回undefined.

    var trees = new Array("redwood", "bay", "cedar", "oak", "maple");
    delete trees[3];
    if (3 in trees) {
      // this does not get executed(不会被执行)
    }
    

    如果想让数组中存在一个元素但是是undefined值,使用undefined关键字而不是delete操作. 如下: trees[3]分配一个undefined,但是这个数组元素仍然存在:

    var trees = new Array("redwood", "bay", "cedar", "oak", "maple");
    trees[3] = undefined;
    if (3 in trees) {
      // this gets executed(会被执行)
    }
    

    in

    in操作,如果指定的属性在指定的对象中会返回true,语法如下:

    propNameOrNumber in objectName
    

    wherepropNameOrNumber是一个字符串或数值表达式代表一个属性名或数组索引objectName是一个对象名.

    下面的例子是 in 操作的常见用法.

    // Arrays
    var trees = new Array("redwood", "bay", "cedar", "oak", "maple");
    0 in trees;        // returns true
    3 in trees;        // returns true
    6 in trees;        // returns false
    "bay" in trees;    // returns false (you must specify the index number,
                       // not the value at that index)
    "length" in trees; // returns true (length是数组的属性)
    
    // Predefined objects
    "PI" in Math;          // returns true
    var myString = new String("coral");
    "length" in myString;  // returns true
    
    // Custom objects
    var mycar = {make: "Honda", model: "Accord", year: 1998};
    "make" in mycar;  // returns true
    "model" in mycar; // returns true
    

    instanceof

    instanceof 操作,如果对象是某种指定类型返回ture.语法如下:

    objectName instanceof objectType
    

    objectName 是对象的名称相较于objectType,objectType是对象的类型, 例如DateArray.

    当你需要确认一个对象在运行时的类型时使用instanceof.例如, 抓取异常, 你可以根据抛出异常的类型分类处理异常代码.

    例如, 下面的代码使用instanceof去判断 theDay是否是一个 Date 对象. 因为theDay是一个Date对象, 所以if中的代码会执行.

    var theDay = new Date(1995, 12, 17);
    if (theDay instanceof Date) {
      // statements to execute 执行
    }
    

    new

    You can use the new operator to create an instance of a user-defined object type or of one of the predefined object types Array, Boolean, Date, Function, Image, Number, Object, Option, RegExp, or String. On the server, you can also use it with DbPool, Lock, File, or SendMail. Use new as follows:

    var objectName = new objectType([param1, param2, ..., paramN]);
    

    You can also create objects using object initializers, as described in using object initializers.

    See the new operator page in the Core JavaScript Reference for more information.

    this

    Use the this keyword to refer to the current object. In general, this refers to the calling object in a method. Use this as follows:

    this["propertyName"]
    
    this.propertyName
    

    Example 1.
    Suppose a function called validate validates an object's value property, given the object and the high and low values:

    function validate(obj, lowval, hival){
      if ((obj.value < lowval) || (obj.value > hival))
        alert("Invalid Value!");
    }
    

    You could call validate in each form element's onChange event handler, using this to pass it the form element, as in the following example:

    <B>Enter a number between 18 and 99:</B>
    <INPUT TYPE="text" NAME="age" SIZE=3
       onChange="validate(this, 18, 99);">
    

    Example 2.
    When combined with the form property, this can refer to the current object's parent form. In the following example, the form myForm contains a Text object and a button. When the user clicks the button, the value of the Text object is set to the form's name. The button's onClick event handler uses this.form to refer to the parent form, myForm.

    <FORM NAME="myForm">
    Form name:<INPUT TYPE="text" NAME="text1" VALUE="Beluga">
    <P>
    <INPUT NAME="button1" TYPE="button" VALUE="Show Form Name"
       onClick="this.form.text1.value = this.form.name;">
    </FORM>
    

    typeof

    The typeof operator is used in either of the following ways:

    1. typeof operand
      
    2. typeof (operand)
      

    The typeof operator returns a string indicating the type of the unevaluated operand. operand is the string, variable, keyword, or object for which the type is to be returned. The parentheses are optional.

    Suppose you define the following variables:

    var myFun = new Function("5 + 2");
    var shape = "round";
    var size = 1;
    var today = new Date();
    

    The typeof operator returns the following results for these variables:

    typeof myFun;     // returns "function"
    typeof shape;     // returns "string"
    typeof size;      // returns "number"
    typeof today;     // returns "object"
    typeof dontExist; // returns "undefined"
    

    For the keywords true and null, the typeof operator returns the following results:

    typeof true; // returns "boolean"
    typeof null; // returns "object"
    

    For a number or string, the typeof operator returns the following results:

    typeof 62;            // returns "number"
    typeof 'Hello world'; // returns "string"
    

    For property values, the typeof operator returns the type of value the property contains:

    typeof document.lastModified; // returns "string"
    typeof window.length;         // returns "number"
    typeof Math.LN2;              // returns "number"
    

    For methods and functions, the typeof operator returns results as follows:

    typeof blur;        // returns "function"
    typeof eval;        // returns "function"
    typeof parseInt;    // returns "function"
    typeof shape.split; // returns "function"
    

    For predefined objects, the typeof operator returns results as follows:

    typeof Date;     // returns "function"
    typeof Function; // returns "function"
    typeof Math;     // returns "object"
    typeof Option;   // returns "function"
    typeof String;   // returns "function"
    

    void

    The void operator is used in either of the following ways:

    1. void (expression)
      
    2. void expression
      

    The void operator specifies an expression to be evaluated without returning a value. expression is a JavaScript expression to evaluate. The parentheses surrounding the expression are optional, but it is good style to use them.

    You can use the void operator to specify an expression as a hypertext link. The expression is evaluated but is not loaded in place of the current document.

    The following code creates a hypertext link that does nothing when the user clicks it. When the user clicks the link, void(0) evaluates to undefined, which has no effect in JavaScript.

    <A HREF="javascript:void(0)">Click here to do nothing</A>
    

    The following code creates a hypertext link that submits a form when the user clicks it.

    <A HREF="javascript:void(document.form.submit())">
    Click here to submit</A>

    Operator precedence

    The precedence of operators determines the order they are applied when evaluating an expression. You can override operator precedence by using parentheses.

    The following table describes the precedence of operators, from highest to lowest.

    In accordance with relevant discussion, this table was reversed to list operators in decreasing order of priority.

    Table 3.7 Operator precedence
    Operator type Individual operators
    member . []
    call / create instance () new
    negation/increment ! ~ - + ++ -- typeof void delete
    multiply/divide * / %
    addition/subtraction + -
    bitwise shift << >> >>>
    relational < <= > >= in instanceof
    equality == != === !==
    bitwise-and &
    bitwise-xor ^
    bitwise-or |
    logical-and &&
    logical-or ||
    conditional ?:
    assignment = += -= *= /= %= <<= >>= >>>= &= ^= |=
    comma ,

    A more detailed version of this table, complete with links to additional details about each operator, may be found in JavaScript Reference.

    文档标签和贡献者

    最后编辑者: z_p_p,