Chapter 4: Expressions and Operators
1. What is an operand and what is a result type?
In computer programming and computer science, operands refer to the values or data that participate in a calculation or operation . Operands can be numbers, variables, constants , or expressions, depending on the specific calculation or operation. Operands are used in various calculations, such as arithmetic operations, logical operations, bitwise operations, etc.
- Example of operands:
- In arithmetic operations, the operands are usually the numbers involved in the operation, such as two numbers in addition: 2 + 3. 2 and 3 here are the operands.
- In logical operations, the operands are values used for logical judgments, such as Boolean expressions:
a && b
. Here a and b are the operands, and their values are true or false (true or false). - In bitwise operations, the operands are values that are operated on at the binary bit level, such as the bitwise AND (&) operation:
a & b
. Here a and b are binary numbers used for bitwise AND operations.
The number of operands depends on the type of operator. For example, unary operators (such as the negation operator "!") require only one operand, while binary operators (such as the addition operator "+") require two operands.
Result Type refers to the data type of the result of an operation or operation. When an operation or operation is performed on an operand, a result will be obtained according to the rules of the operator and the data type of the operand. The data type of this result is the result type.
- Examples of result types:
- In arithmetic operations, the result of adding two integers is an integer, so the result type is an integer type.
- In logical operations, the result of logical AND operation is a Boolean value (true or false), so the result type is Boolean type.
- In bitwise operations, the result of the bitwise AND operation is a new binary number, so the result type is a binary type.
Result types are important to ensure correctness and consistency of calculations. In programming, if operations are performed on operands of different types, the programming language will automatically perform type conversion to obtain a reasonable result type.
For example, in JavaScript:
javascriptCopy code
const x = 5; // x是一个整数 const y = 2.5; // y是一个浮点数 const result = x + y; // 进行算术运算,结果为7.5,result的类型为浮点数
In this example, x is an integer and y is a floating point number, and their data types are different. But when adding, JavaScript automatically converts integers to floating point numbers to get the correct result type. The result is a floating point number.
example:
String methods
Replace string content
The replace() method replaces the value specified in the string with another value
Convert to uppercase and lowercase
Convert string to uppercase via toUpperCase()
concat() method
concat() concatenates two or more strings
var text = "Hello" + " " + "World!";
var text = "Hello".concat(" ", "World!");
String.trim()
The trim() method removes whitespace characters at both ends of the string
var str = " Hello World! ";
alert(str.trim());
charAt() method
The charAt() method returns the string at the specified subscript (position) in the string.
charCodeAt() method
The charCodeAt() method returns the unicode encoding of the character at the specified index in the string.
Convert string to array
You can convert the string into an array through split()
var txt = "a,b,c,d,e"; // String
txt.split(","); // Separate variable arrays with commas
txt.split(" "); // Separate by spaces
txt.split("|"); // Split on pipe
Practice questions:
Find the position of txt
a character in a string h
.
var txt = "abcdefghijklm"; var pos = txt.indexOf("h"); // 7
numerical value
var x = "100";
var y = "10";
var z = x / y; // z will be 10
var x = "100";
var y = "10";
var z = x * y; // z will be 1000
var x = "100";
var y = "10";
var z = x - y; // z will be 90
var x = "100";
var y = "10";
var z = x + y; // z won't be 110 (it will be 10010)
Can be replaced by
var x = '100'; var y = '10'; var z = parseInt( x ) + parseInt( y ) ; console.log(z); // output:110
NaN - not a numeric value
var x = 100 / "Apple"; // x will be NaN (not a number)
var x = 100 / "10"; // x will be 10
var x = 100 / "Apple";
isNaN(x); // returns true because x is not a number
hexadecimal
JavaScript will interpret numeric constants prefixed with 0x as hexadecimal
Use the toString() method to output the number as hexadecimal, octal or binary.
Hexadecimal is based on base 16. Decimal is based on base 10. Octal is base 8. Binary is base 2.
var myNumber = 32;
myNumber.toString(10); // Returns 32
myNumber.toString(32); // Returns 10
myNumber.toString(16); // Returns 20
myNumber.toString(8); // Returns 40
myNumber .toString(2); // Return 100000
Number methods and properties
var x = 123; x.toString (); // Return 123 from
variable 23 return 123
toExponential() method
toExponential() returns a string value containing a number that has been rounded using exponential notation
var x = 9.656;
x.toExponential(2); // returns 9.66e+0
toFixed() method
toFixed() returns a string value containing a number with the specified number of decimal places
var x =
9.656
;
toPrecision() method
toPrecision() returns a string value containing a number of specified length
var x = 123; x.valueOf (); // Return 123 from
variable 23 return 123
Convert variable to numeric value
These three JavaScript methods can be used to convert variables to numbers:
- Number() method var z = Number(x)+Number(y)
- parseInt() method var z = parseInt(x)+parseInt(y) //Parse a string and return a value. Spaces are allowed. Return only the first number
- The parseFloat() method var z = parseFloat(x)+parseFloat(y) parses a string and returns a numerical value. Spaces are allowed. Return only the first number
These methods are not numeric methods, but global JavaScript methods.
Numerical operations
Math.round()
The return value of Math.round(x) is x rounded to the nearest integer
Math.pow()
The return value of Math.pow(x, y) is x raised to the y power:
Math.sqrt()
Math.sqrt(x) returns the square root of x:
Math.sqrt(64); // returns 8
Math.abs()
Math.abs(x) returns the absolute (positive) value of x:
Math.abs(-4.7); // returns 4.7
Math.ceil()
The return value of Math.ceil(x) is the nearest integer rounded to x:
Math.ceil(4.4); // returns 5
Math.floor()
The return value of Math.floor(x) is the nearest integer rounded down to x
Math.floor(4.7); // returns 4
Math.sin()
Math.sin(x) Returns the sine (a value between -1 and 1) of the angle x in radians.
If you wish to use angles instead of radians, you need to convert the angles to radians:
Angle in radians = Angle in degrees x PI / 180.
Math.sin(90 * Math.PI / 180); // Returns 1 (sine of 90 degrees)
Math.min() and Math.max()
Math.min() and Math.max() can be used to find the lowest or highest value in a parameter list:
random number
array
An array is a special type of variable that can store more than one value at a time.
Array.foreach() function
Add array elements
The best way to add new elements to an array is to use the push() method
associative array
Many programming elements support named-indexed arrays.
Arrays with named indexes are called associative arrays (or hashes).
JavaScript does not support named indexed arrays.
In JavaScript, arrays can only be indexed numerically .
var person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
var x = person.length; // person.length will return 3
var y = person [0]; // person[0] will return "John"
Avoid new Array()
There is no need to use JavaScript's built-in array constructor new Array().
Please use [] instead!
The following two different statements create a new empty array named points:
var points = new Array(); // bad
var points = []; // good
Convert array to string
JavaScript method toString() converts an array into a string of array values (comma separated)
The join() method can also combine all array elements into a string.
It behaves similarly toString()
, but you can also specify the delimiter
var ff = [34,5,6,77,8]
undefined
ff.join() // '34,5,6,77,8'
But if you want to remove the commas in the string, you can write
var ff = [34, 5, 6, 77, 8]; // Use empty string as delimiter to concatenate the elements of the array
var joinedString = ff.join(" ");
console.log(joinedString); // Output: "3456778"
Popping 和 Pushing
When working with arrays, removing elements and adding new ones is simple.
Popping and Pushing refer to:
Pop an item from an array , or push an item to an array.
where s = [1,2,33,22]
s.pop() // [1,2,33]
s.push(55) // [1,2,33,55]
displacement element
Offset is equivalent to popping, but deals with the first element instead of the last.
The shift() method deletes the first array element and "shifts" all other elements to lower indices
The unshift() method ( at the beginning ) adds new elements to the array and "reverse shifts" the old elements
Delete element
Since JavaScript arrays are objects, elements in them can be deleted using the JavaScript delete operator
splice array
The splice() method can be used to add new items to an array:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 2, "Lemon", "Kiwi");
['Apple', 'Mango']0: "Apple"1: "Mango"length: 2[[Prototype]]: Array(0)
fruits
['Banana', 'Orange', 'Lemon', 'Kiwi']
Use splice() to remove elements
With clever parameterization, you can use splice() to remove elements without leaving "holes" in the array.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(0, 1); // Remove the first element of fruits
Merge (concatenate) arrays
The concat() method creates a new array by merging (concatenating) existing arrays:
Example (merging three arrays)
var arr1 = ["Cecilie", "Lone"];
var arr2 = ["Emil", "Tobias", "Linus"];
var arr3 = ["Robin", "Morgan"];
var myChildren = arr1.concat(arr2, arr3);
Crop array
The slice() method slices a new array from a slice of the array.
This example cuts out an array starting from array element 1 ("Orange"):
method:
Array sort
The sort() method sorts an array in alphabetical order:
The reverse() method reverses the elements in an array.
You can use this to sort an array in descending order:
ratio function
The purpose of comparison functions is to define an alternative sort order.
The comparison function should return a negative, zero or positive value, depending on the arguments:
Using Math.max() on arrays
You can use Math.max.apply to find the highest value in an array:
Using Math.min() on arrays
You can use Math.min.apply to find the lowest value in an array:
Math.min.apply([1, 2, 3]) is equal to Math.min(1, 2, 3).
JavaScript array iteration
The forEach() method calls a function (callback function) once for each array element
var l = '';
var number = [33, 4, 56, 67];
number.forEach(function(element) { // In this callback function, element is the current element in the array
l += element + ' ';
//Add the current element to variable l, separated by spaces
});
Array.map()
The map() method creates a new array by executing a function on each array element.
The map() method will not perform a function on array elements that have no values.
The map() method does not change the original array.
This example multiplies each array value by 2:
//original array
var numbers = [1, 2, 3, 4, 5];
// Use map() to multiply each number by 2 and return the new array
var a = numbers.map(function(number) { return number * 2; });
console.log(a); // Output: [2, 4, 6, 8, 10]
Array.filter() is used to create a new array containing elements that meet a condition
The filter() method creates a new array containing the array elements that pass the test.
Array.every() is used to check whether all elements of the array meet the condition.
every() method checks whether all array values pass the test.
Array.some() is used to check whether at least one element of the array meets the condition.
The some() method checks whether certain array values pass the test.
This example checks if certain array values are greater than 18:
Array.reduce() starts with the first element of the array and performs reduction operations from left to right.
The reduce() method runs a function on each array element to produce (reduce it) a single value.
The reduce() method works from left to right in the array. See also reduceRight().
The reduce() method does not reduce the original array.
Array.reduceRight() starts from the last element of the array and performs the reduction operation from right to left.
The reduceRight() method runs a function on each array element to produce (reduce it) a single value.
The reduceRight() method works from right to left in the array. See also reduce().
The reduceRight() method does not reduce the original array.
Array.indexOf()
The indexOf() method searches an array for an element value and returns its position.
Note: The first item's position is 0, the second item's position is 1, and so on.
Array.lastIndexOf()
Array.lastIndexOf() is like Array.indexOf(), but searches from the end of the array.
Array.find()
The find() method returns the value of the first array element that passes the test function.
This example finds (returns) the value of the first element greater than 18:
Array.findIndex()
The findIndex() method returns the index of the first array element that passes the test function.
This example finds the index of the first element greater than 18:
JavaScript date methods
JavaScript boolean operators
JavaScript comparison operators
JavaScript if else statement
JavaScript Switch statement
JavaScript For Loop
JavaScript data types
JavaScript strict mode
JavaScript Arrow arrow function
Object method ()
Usage of call()
apply() to remove duplicates
1. Destructuring assignment:
Destructuring assignment allows you to extract values from an array or object and assign them to variables, making the code more concise and readable.
javascriptCopy code
const [a, b] = [1, 2]; // a = 1, b = 2 const { firstName, lastName } = person; // 从对象中提取属性值
2. Extended syntax and remaining parameters:
Extended syntax allows for quick copying of arrays or objects, while rest parameters allow you to receive an unlimited number of parameters and collect them into an array.
javascriptCopy code
const array1 = [1, 2, 3]; const array2 = [...array1, 4, 5]; // [1, 2, 3, 4, 5] function sum(...numbers) { return numbers.reduce((acc, num) => acc + num, 0); }
3. Promise and asynchronous programming:
Promises are one way of handling asynchronous operations that can better manage callback hell.
javascriptCopy code
function fetchData() { return new Promise((resolve, reject) => { // 异步操作 if (success) { resolve(data); } else { reject(error); } }); } fetchData() .then(data => console.log(data)) .catch(error => console.error(error));
4. Arrow function:
Arrow functions provide a more concise syntax for defining functions and automatically capture the context this
value.
javascriptCopy code
const multiply = (a, b) => a * b; const person = { name: 'John', sayHi: () => { console.log(`Hello, ${this.name}`); // 这里的 this 不是 person 对象 } };
5. Class inheritance and extension:
JavaScript supports class-based inheritance, which enables you to create a class and inherit the properties and methods of another class.
javascriptCopy code
class Animal { constructor(name) { this.name = name; } speak() { console.log(`${this.name} makes a sound.`); } } class Dog extends Animal { speak() { console.log(`${this.name} barks.`); } }
What is a Promise?
Promise is a programming model in JavaScript for handling asynchronous operations. It allows you to write and manage asynchronous code in a more intuitive way, avoiding the problem of callback hell. A Promise represents an operation that may complete or fail in the future, and provides a structure for handling the results or errors after the operation completes.
Promise consists of the following three states:
-
Pending : Initial status, indicating that the operation has not been completed or failed.
-
Fulfilled : Indicates that the operation was successfully completed and carries a value (result).
-
Rejected (failed) : Indicates that the operation failed, usually carrying an error object indicating the reason for the failure of the operation.
The role of Promise:
-
More readable asynchronous code : Promises make asynchronous code more readable and more like synchronous code. It avoids multiple levels of nested callback functions and improves code readability and maintainability.
-
Handling asynchronous processes : Promises allow you to perform a series of asynchronous operations in sequence, with each operation depending on the result of the previous operation. This allows for better organization of asynchronous code and makes it more logical.
-
Handling errors : Promises allow you to catch and handle errors in chained operations. You can use
.catch()
the method to catch any errors in the chain, thus providing better error handling mechanism. -
Parallel Execution : Using
Promise.all()
, you can execute multiple asynchronous operations in parallel and get the results when they all complete. This can improve performance in some cases.
Basic usage of Promise:
The following is a simple Promise example that shows how to create, handle and use Promise objects:
javascriptCopy code
// 创建一个 Promise,表示异步操作 const myPromise = new Promise((resolve, reject) => { setTimeout(() => { const randomNumber = Math.random(); if (randomNumber > 0.5) { resolve(randomNumber); // 操作成功完成 } else { reject(new Error("Random number is too small")); // 操作失败 } }, 1000); }); // 使用 Promise myPromise .then((fulfilledValue) => { console.log("Promise fulfilled with value:", fulfilledValue); }) .catch((error) => { console.error("Promise rejected with error:", error); });
In this example, it may change to the or state myPromise
after 1 second , delivering the result or error as appropriate.fulfilled
rejected
In short, Promise is a powerful pattern for handling asynchronous operations, which can help you write asynchronous code more clearly, handle errors, and control the flow.