02.JavaScript的14种表达式与操作符

An expression is a phrase of JavaScript that can be evaluated to produce a value.For simplicity, we sometimes say that an operator returns a value rather than “evaluates to” a value.

1.Primary Expressions

Primary expressions in JavaScript are constant or literal values, certain language keywords, and variable references.

//Literals are constant values that are embedded directly in your program.
1.23         // A number literal
"hello"      // A string literal
/pattern/    // A regular expression literal
// Some of JavaScript’s reserved words are primary expressions:
true       // Evalutes to the boolean true value
false      // Evaluates to the boolean false value
null       // Evaluates to the null value
this       // Evaluates to the "current" object
// a reference to a variable, constant, or property of the global object
i             // Evaluates to the value of the variable i.
sum           // Evaluates to the value of the variable sum.
undefined     // The value of the "undefined" property of the global object

2.Object and Array Initializers

Object and array initializers are expressions whose value is a newly created object or array. These initializer expressions are sometimes called object literals and array literals.

// array literals
[]         // An empty array: no expressions inside brackets means no elements
[1+2,3+4]  // A 2-element array.  First element is 3, second is 7
let matrix = [[1,2,3], [4,5,6], [7,8,9]];
let sparseArray = [1,,,,5];

// object literals
let p = { x: 2.3, y: -1.2 };  // An object with 2 properties
let q = {};                   // An empty object with no properties
q.x = 2.3; q.y = -1.2;        // Now q has the same properties as p

let rectangle = {
    upperLeft: { x: 2, y: 2 },
    lowerRight: { x: 4, y: 5 }
};

3.Function Definition Expressions

In a sense, a function definition expression is a “function literal” in the same way that an object initializer is an “object literal.”

/ This function returns the square of the value passed to it.
let square = function(x) { return x * x; };

4.Property Access Expressions

A property access expression evaluates to the value of an object property or an array element. JavaScript defines two syntaxes for property access:

let o = {x: 1, y: {z: 3}}; // An example object
let a = [o, 4, [5, 6]];    // An example array that contains the object
o.x                        // => 1: property x of expression o
o.y.z                      // => 3: property z of expression o.y
o["x"]                     // => 1: property x of object o
a[1]                       // => 4: element at index 1 of expression a
a[2]["1"]                  // => 6: element at index 1 of expression a[2]
a[0].x                     // => 1: property x of expression a[0]
//  Conditional Property Access
expression ?. identifier
expression ?.[ expression ]

5.Invocation Expressions

An invocation expression is JavaScript’s syntax for calling (or executing) a function or method.

f(0)            // f is the function expression; 0 is the argument expression.
Math.max(x,y,z) // Math.max is the function; x, y, and z are the arguments.
a.sort()        // a.sort is the function; there are no arguments.
//  Conditional Invocation
function square(x, log) { // The second argument is an optional function
    log?.(x);             // Call the function if there is one
    return x * x;         // Return the square of the argument
}

6.Object Creation Expressions

An object creation expression creates a new object and invokes a function (called a constructor) to initialize the properties of that object.

此处最符合函数式编程的范式,特意点出用function。

7.Operator Overview

Operators are used for JavaScript’s arithmetic expressions, comparison expressions, logical expressions, assignment expressions, and more.

8.Arithmetic Expressions

// 1 The + Operator
// 2 Unary Arithmetic Operators
Unary plus (+)
Unary minus (-)
Increment (++)
Decrement (--)
//此处的术语抽象得好哇...
//3 Bitwise Operators
Bitwise AND (&)
Bitwise OR (|)
Bitwise XOR (^)
Bitwise NOT (~)
Shift left (<<)
Shift right with sign (>>)
Shift right with zero fill (>>>)

9.Relational Expressions

// The in Operator
let point = {x: 1, y: 1};  // Define an object
"x" in point               // => true: object has property named "x"
"z" in point               // => false: object has no "z" property.
"toString" in point        // => true: object inherits toString method
let data = [7,8,9];        // An array with elements (indices) 0, 1, and 2
"0" in data                // => true: array has an element "0"
1 in data                  // => true: numbers are converted to strings
3 in data                  // => false: no element 3

//The instanceof Operator
let d = new Date();  // Create a new object with the Date() constructor
d instanceof Date    // => true: d was created with Date()
d instanceof Object  // => true: all objects are instances of Object
d instanceof Number  // => false: d is not a Number object
let a = [1, 2, 3];   // Create an array with array literal syntax
a instanceof Array   // => true: a is an array
a instanceof Object  // => true: all arrays are objects
a instanceof RegExp  // => false: arrays are not regular expressions

10.Logical Expressions

Logical AND (&&)
Logical OR (||)
Logical NOT (!)

11.Assignment Expressions

The assignment operator has right-to-left associativity:

i = j = k = 0;       // Initialize 3 variables to 0
// Assignment with Operation
total += salesTax;

12.Evaluation Expressions

eval("function f() { return x+1; }");

13 Miscellaneous Operators

// 1 The Conditional Operator (?:)
x > 0 ? x : -x     // The absolute value of x
// 2 First-Defined (??)
(a !== null && a !== undefined) ? a : b
a ?? b
// 3 The typeof Operator
(typeof value === "string") ? "'" + value + "'" : value.toString()
// 4 The delete Operator
let o = { x: 1, y: 2}; // Start with an object
delete o.x;            // Delete one of its properties
"x" in o               // => false: the property does not exist anymore
//5 The await Operator
//6 The void Operator
let counter = 0;
const increment = () => void counter++;
increment()   // => undefined
counter       // => 1
// 7 The comma Operator (,)

14 Summary

This chapter covers a wide variety of topics, and there is lots of reference material here that you may want to reread in the future as you continue to learn JavaScript. Some key points to remember, however, are these:

Expressions are the phrases of a JavaScript program.

Any expression can be evaluated to a JavaScript value.

Expressions can also have side effects (such as variable assignment) in addition to producing a value.

Simple expressions such as literals, variable references, and property accesses can be combined with operators to produce larger expressions.

JavaScript defines operators for arithmetic, comparisons, Boolean logic, assignment, and bit manipulation, along with some miscellaneous operators, including the ternary conditional operator.

The JavaScript + operator is used to both add numbers and concatenate strings.

The logical operators && and || have special “short-circuiting” behavior and sometimes only evaluate one of their arguments. Common JavaScript idioms require you to understand the special behavior of these operators.

展开阅读全文

页面更新:2024-05-15

标签:范式   表达式   抽象   术语   函数   操作   科技

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top