JavaScript usage misunderstandings
In this chapter we will discuss misunderstandings in the use of JavaScript.
String replace
We often use string’s replace method to replace certain characters in string. The syntax is like this
string.replace(subStr/reg,replaceStr/function)
The first parameter is the string to be found or a regular expression, and the second parameter is To replace a string or a method, we can use
"I'm Byron".replace("B","b") // I'm byron
The demerits are the same as we thought, but
"I'm a student, and you?".replace("n","N"); // I'm a studeNt, and you?
Unlike what we expected, the second 'n' was not replaced. If a string is passed as the first argument to the replace method of a string, only the first match will be replaced. If you want to replace all matches, you need to pass in a RegExp object and specify its global property.
"I'm a student, and you?".replace(/n/g,"N"); // I'm a studeNt, aNd you?
typeof
The most misunderstood thing about typeof is typeof It is an operator, not a function, which means we don’t need to add parentheses when judging the type of a variable, we can just use it directly
typeof 1; //numbertypeof(1); //number, there is no need to do this Writing, but that’s right, it’s equivalent to wrapping a variable or constant.
The return value of typeof is a string. In most cases, the returned result is the same as our expected result, but there are A few points to note. We know that JavaScript has several basic types, number, string, boolean, null, undefined, and then object. Let’s look at a few examples
typeof 123; // number
typeof NaN //number
typeof "123" //string
##typeof false; //boolean
typeof undefined ; //undefined
##typeof null //objecttypeof new Array(); //object
##typeof (new Array()); //If you feel it is not clear enough, you can use it this way, the result will be the same
typeof (function(){}); //function
typeof a; //undefined
1. 123 is a number Return number
2. Although NaN means it is not a number, typeof will still return number
3. "123" becomes a string, so string
4 is returned. false The type is boolean
5. The type of undefined is undefined. A variable of this type can only have one literal value "undefined"
6. The type of null is not null, but object, so we don't put our hope in it. Use typeof to help us determine null
7. If typeof determines that it is an object, it will only return object, and will not return the specific types of Array and Date
9. Function is also a type of object. It is said that Object should also be returned directly. But typeof treats it differently and returns function. We can use this to determine whether the variable is a function
10. Undefined variables also return undefined
if and ==
In JavaScript, if does not just judge boolean to determine true or false, 0, NaN, "", undefined, null, false will all be Consider it false
if (!false) {
console.log(1);
} ;
## if (!0) {
## console.log(2);};
## if (!"") {
console.log(3);
};
if (!undefined) {
## console.log(4);
};
if (!null) {
## console.log(5);
};
if (!NaN) {
console.log(6);
};
123456 will be printed out in the consoleBut this does not mean that these values == false
0==false; //true
"0"==false; //true, this is also true
undefined== false //false
null==false //false
null==null //true
NaN==NaN //false
null==undefined //true
Assignment operator application error
In JavaScript programs, if you use the equal sign (=) of the assignment operator in an if conditional statement, an incorrect result will be generated. The correct method is to use a comparison operator The two equal signs (==).
The if conditional statement returns false (which is what we expected) because x is not equal to 10:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> </head> <body> <p id="demo"></p> <script> var x = 0; document.getElementById("demo").innerHTML = Boolean(x == 10); </script> </body> </html>
Common errors in comparison operators
In strict comparison operations, === is the identity operator and checks the value and type of the expression at the same time. The following if conditional statement returns false:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> </head> <body> <p id="demo"></p> <script> var x = 10; var y = "10"; document.getElementById("demo").innerHTML = Boolean(x === y); </script> </body> </html>
This kind of error often occurs in switch statements. The switch statement will use the identity operator (===) for comparison
The following examples will not execute the alert pop-up window due to inconsistent types:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> </head> <body> <p id="demo"></p> <script> var x = 10; switch(x) { case "10": alert("Hello"); } </script> </body> </html>
Addition Notes on Connections
Addition is the addition of two numbers.
The connection is the connection of two strings.
JavaScript uses the + operator for both addition and concatenation.
Next we can see the difference between adding two numbers and concatenating numbers and strings through examples:
var x = 10 + 5; // The result of x is 15
var x = 10 + "5"; // The result of x is "105"
# #
Notes on using floating-point data
All data in JavaScript is stored as 64-bit floating-point data (float).
All programming languages, including JavaScript, have difficulty determining the accuracy of floating-point data:
var x = 0.1;
var y = 0.2;
var z = x + y // The result of z is 0.3
if (z == 0.3) // Return false
Notes on using the Return statement
JavaScript automatically ends at the last line of code by default.
The following example results will return undefined:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> </head> <body> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = myFunction(55); function myFunction(a) { var power = 10; return a * power; } </script> </body> </html>
Why is there such a result? Because in JavaScript, the code of Example 4 is consistent with the following code:
function myFunction(a) {
var
power = 10;
return; // semicolon End, return undefined
a * power;
}
Analysis
If it is an incomplete statement, it is as follows:
var
JavaScript will try to read the second line of statements:
power = 10;
But since a statement like this is complete:
return
JavaScript will automatically close the statement:
return;
In JavaScript, semicolons are optional.
Because return is a complete statement, JavaScript will close the return statement.
Using names to index into arrays
Many programming languages allow the use of names as indexes into arrays.
An array that uses names as indexes is called an associative array (or hash).
JavaScript does not support using names to index arrays, only numeric indexes are allowed.
var person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
var x = person.length; // person.length returns 3
var y = person[0]; // person[0] returns "John"
var person = [];person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
var x = person.length; // person.length returns 0
var y = person[0]; // person[0] returns undefined
##define array elements , the comma cannot be added at the end
Wrong definition:
points = [40, 100, 1, 5, 25, 10,];
Correct definition:
Define the object, you cannot add a comma at the end
Wrong definition method:
websites = {site:"php Chinese website", url :"www.php.cn", like:460,}
Correct definition:
Undefined is not Null
In JavaScript, null is used for objects, and undefined is used for variables, properties and methods.
The object may be null only if it is defined, otherwise it is undefined.
If we want to test whether the object exists, an error will be thrown if the object is not defined yet.
Incorrect usage:
if (myObj !== null && typeof myObj !== "undefined")
The correct way is that we need to use typeof first to detect whether the object is defined:
if (typeof myObj !== "undefined" && myObj !== null)