null and undefined
undefined is equivalent to a variable and does not have an explicit assignment (whether it is assigned, may inadvertently ignore, logical problems) JS's weird is that undefined is really a can use the value.
> var foo;
> foo
undefined
Similarly, JavaScript assigns a undefined when missing parameters:
> function ID (x) {return x}
> ID ()
undefined
a = 1;
A!== undefined//true
a = undefined
var b
a = = b//true
Null is the equivalent of a variable being explicitly specified without a value, rather than being ignored for unexpected reasons (assignment null, proper logic)
Participating operations
JS NULL if entered into the operation, will really be resolved to be 0 or false:
(1 + null) # 1 (1 * null) # 0 (1 * null) # Infinity
Undefined into operation, all get Nan:
(1 + undefined) # nan (1 * undefined) # Nan (1/undefined) # Nan
Logical judgment
null and undefined are considered false when they are logically judged.
Using only one judgment, you can verify that both are true:
will also put false,-0, +0, NaN and ' as null '
if (v) {//V
has value
} else {
//V No value
}
But when you hit the Big Hole,
var foo;
Console.log (foo = = null); True
console.log (foo = = undefined);//True
console.log (foo = = null);//False
console.log (foo = = Unde fined); True
console.log (null = = undefined);//True
Good practices, all use = =
To determine if a quantity is defined and not NULL, use only: if (a!== null && a!== undefined).
= = = and = =
1.== is used to determine whether two values are equal
When two value types are not the same, an automatic conversion occurs, and the resulting results are very counter-intuitive, which may not be the result you want.
"" = 0 "//false
0 =" "//true
0 = =" 0 "//true
false = =" false "//false
= =" 0 "//TRUE
false = = undefined//False
= = NULL//false
NULL = = undefined//True
"\t\r\n" = 0//True
2.===
Type + value comparison
"If the operands on both sides have the same type and value, = = = Return true,!== returns FALSE." "-JavaScript: The Essence of Language"
Best Practices:
Use = = = and!== at any time in the comparison operation
JSON operations
var person = {name: ' Saad ', age:26, department: {id:15, Name: ' R&d '}};
var Stringfromperson = json.stringify (person);
/* Stringfromperson is equal to "{" Name ":" Saad "," Age ":" department ": {" ID ":" "Name": "R&d"} " * *
var personfromstring = Json.parse (Stringfromperson);
/* personfromstring is equal to Person object *
/to string
var obj = {
name: ' MyObj '
};
Json.stringify (obj);
function objects and anonymous functions
Function Object Assignment
var slice_func = [].slice
//slice_func ()
var a = function () {
};
A ()
var a = {
fun:function () {
};
}
A.fun ()
someelement.addeventlistener ("click", Function (e) {
//I ' m anonymous!
});
And
var f = function foo () {return
typeof foo;//foo is valid within scope
};
Foo is used externally for
typeof Foo;//"Undefined"
f ();//"function"
anonymous functions
From
var name = ' Chris ';
var age = '% ';
var status = ' single ';
function Createmember () {
//[...]
}
function Getmemberdetails () {
//[...]
}
To
var myapplication = function () {
var name = ' Chris ';
var age = '% ';
var status = ' single ';
return{
createmember:function () {
//[...]
},
getmemberdetails:function () {
//[...]
}}
} ();
Myapplication.createmember () and
//Myapplication.getmemberdetails () now works.
Best practices
1. When defining multiple variables, omit the var keyword and replace it with commas
var Someitem = ' some string ';
var Anotheritem = ' another string ';
var onemoreitem = ' One more string ';
A better way
var Someitem = ' Some string ',
Anotheritem = ' Another string ',
Onemoreitem = ' one more string ';
2. Remember, do not omit semicolons, do not omit curly braces
Omitting semicolons may result in larger, unknown, and difficult to discover problems
var Someitem = ' Some string '
function dosomething () {return
' something '
}
A better way
var Someitem = ' some string ';
function dosomething () {return
' something ';
}
3. Use {} instead of new Ojbect ()
There are a number of ways to create objects in JavaScript. Perhaps the traditional approach is to use the "new" addition constructor, as follows:
var o = new Object ();
O.name = ' Jeffrey ';
O.lastname = ' Way ';
O.somefunction = function () {
console.log (this.name);
}
A better way
var o = {
name: ' Jeffrey ',
lastName = ' Way ',
somefunction:function () {
console.log (this.name);
}
};
As long as multiple global variables are organized in one namespace, the likelihood of a poor interaction with other applications, components, or class libraries is significantly reduced. --douglas Crockford
4. Use [] instead of new Array ()
var a = new Array ();
A[0] = "Joe";
A[1] = ' Plumber ';
A better approach:
var a = [' Joe ', ' Plumber '];
5.typeof judgment
typeof generally can only return the following results: number,boolean,string,function,object,undefined
Expr
typeof xx = = '
typeof xx!== '
e.g.
Numbers
typeof of Panax Notoginseng = = ' number ';
typeof 3.14 = = = ' number ';
typeof Infinity = = = ' number ';
typeof NaN = = ' number '; Although Nan is an abbreviation for "Not-a-number", it means "not a number"
//Strings
typeof "" = = = ' string ';
typeof "Bla" = = = ' string ';
typeof (typeof 1) = = ' String '; typeof return is definitely a string
//Booleans
typeof true = = ' Boolean ';
typeof false = = = ' Boolean ';
Undefined
typeof Undefined = = ' Undefined ';
typeof BlaBla = = ' undefined '; An undefined variable, or a variable that has not been assigned an initial value
//Objects
typeof {A:1} = = = = ' object ';
typeof [1, 2, 4] = = ' object '; Using the Array.isarray or Object.prototype.toString.call method, you can distinguish between an array and a real object
typeof new Date () = = ' object ';
Functions
typeof function () {} = = = ' function ';
typeof Math.sin = = ' function ';
typeof null = = ' object '; This has always been the case since the birth of JavaScript.
6. Ternary operator: powerful and coquettish
Grammar
Expression? xxx:yyy
Bad
var direction;
if (x < MB) {
direction = 1;
} else {
direction =-1;
}
Good
var direction = x < 200? 1:1;
7. Use logical and/or to make conditional judgments
var foo = ten;
Foo = = && dosomething (); Equivalent to if (foo = =) dosomething ();
Foo = = 5 | | DoSomething (); Equivalent to if (foo!= 5) dosomething ();
Default value
A = B | | ' Default ' return
B | | | c | | d > 1? 0:2
8. Don't forget to use the var keyword when assigning values to a variable
Assigning a value to an undefined variable causes a global variable to be created. To avoid global variables
9. Self-invoked function
Either call an anonymous function (self-invoked Anonymous function) or call a function expression (iife-immediately invoked function Expression) immediately. This is a function that is automatically executed immediately after creation
(function () {
//Some private code that would be executed automatically
}) ();
(function (a,b) {
var result = A+b;
return result;
}) (10,20)
10. Avoid using the eval () and function constructors
Eval= Evil, not only dramatically reduces the performance of the script (the JIT compiler cannot predict the content of the string, it cannot be precompiled and optimized), but it also poses a significant security risk because it pays too high a privilege to execute, avoiding
Using the Eval and function constructors is a very expensive operation because each time they invoke the script engine to convert the source code into executable code.
var func1 = new Function (functioncode);
var Func2 = eval (functioncode);
11. Avoid using with ()
using with () inserts a global variable. Therefore, a variable with the same name will be overwritten with the value and cause unnecessary trouble
12. The script is placed at the bottom of the page
Remember-the primary goal is to make the page as fast as possible to the user, the script folder is blocked, the script loaded and executed, the browser can not continue to render the following content. So the user will be forced to wait a long time
13. Avoid declaring variables within a for statement
Bad
for (var i = 0; i < somearray.length i++) {
var container = document.getElementById (' container ');
container.innerhtml + = ' My number: ' + i;
Console.log (i);
}
Good
var container = document.getElementById (' container ');
for (var i = 0, len = somearray.length i < len; i++) {
container.innerhtml + = ' I number: ' + i;
Console.log (i);
}
14. Add comments to Code
Loop the array, outputting each name (note: This comment seems a bit superfluous).
for (var i = 0, len = Array.Length i < len; i++) {
console.log (array[i));
15.instanceof
The Instanceof method requires the developer to explicitly confirm that the object is a specific type
var ostringobject = new String ("Hello World");
Console.log (Ostringobject instanceof String); Output "true"
//To determine if Foo is an instance of the Foo class
function foo () {}
var foo = new Foo ();
Console.log (foo instanceof foo)//true
//Determine if Foo is an instance of the Foo class and whether it is an instance
function Aoo () {} function Foo of its parent type
( {}
Foo.prototype = new Aoo ();//javascript prototype Inherits
var foo = new Foo ();
Console.log (foo instanceof foo)//true
console.log (foo instanceof aoo)//true
16.apply/call
Somefn.call (This, arg1, arg2, arg3);
Somefn.apply (This, [Arg1, Arg2, Arg3]);
Apply
Function.apply (Obj,args) method can receive two parameters
OBJ: This object will replace the This object in the function class
Args: This is an array, which is passed as a parameter to the function (args-->arguments)
Call
Function.call (obj,[param1[,param2[,... [, Paramn]]]
OBJ: This object will replace the This object in the function class
Params: This is a parameter list
Which is used depends on the type of parameter