JavaScript basic learning series twenty-two: exponential operator

ECMAScript 7 added the exponential operator, Math.pow() now has its own operator**, and the result is the same:

console.log(Math.pow(3, 2); // 9

Not only that, the exponential operator also has its own exponential assignment operator **=, which performs the exponential operation and the assignment of the result:

 console.log(Math.pow(16, 0.5); // 4
console.log(16** 0.5);         // 4
 console.log(3 ** 2);           // 9
 let squared = 3;
squared **= 2;
console.log(squared); // 9

1. Additive operator:

Additive operators, the addition and subtraction operators, are generally the simplest operators in programming languages. However, in ECMAScript, these two operators have some special behavior. Similar to the multiplicative operator, the additive operator converts different data types in the background.

If both operands are numeric, the addition operator performs the addition operation and returns the result according to the following rules:

  • If any operand is NaN, return NaN;
  • If it is Infinity plus Infinity, then Infinity is returned;
  • If it is -Infinity plus -Infinity, then -Infinity is returned;
  • If it is Infinity plus -Infinity, NaN is returned;
  • If it is +0 plus +0, then +0 is returned;
  • If it is -0 plus +0, then +0 is returned;
  • If it is -0 plus -0, then -0 is returned.

However, if one of the operands is a string, the following rules apply:

  • If both operands are strings, the second string is concatenated after the first string;
  • If only one operand is a string, convert the other operand to a string and concatenate the two strings together. If any of the operands are objects, numeric values, or Boolean values, their toString() method is called to obtain a string, and then the previous rules for strings are applied. For undefined and null, call the String() function to obtain "undefined" and "null" respectively.
let result1 = 5 + 5;
console.log(result1);
let result2 = 5 + "5";
console.log(result2);
// 两个数值
// 10
// 一个数值和一个字符串 // "55"

Two operation modes of the addition operator. Normally, 5 + 5 equals 10 (numeric value), as shown in the first two lines of code. However, if you change one operand to a string, such as "5", the result of the addition becomes "55" (the original string value), because the first operand is also converted to a string.

let num1 = 5;
    let num2 = 10;
    let message = "The sum of 5 and 10 is " + num1 + num2;
    console.log(message);  // "The sum of 5 and 10 is 510"

Guess you like

Origin blog.csdn.net/wanmeijuhao/article/details/135450047