JavaScript function learning summary and related programming habits guide
- 2020-10-31 21:37:52
- OfStack
null and undefined
The odd thing about JS is that undefined is really a value that can be used.
> var foo;
> foo
undefined
Similarly, when parameters are missing, JavaScript will allocate 1 undefined:
> function id(x) { return x }
> id()
undefined
a = 1;
a !== undefined // true
a = undefined
var b
a === b //true
Null is equivalent to a variable that is explicitly specified to have no value, rather than being ignored for an unexpected reason (null assignment, valid logic)
Participate in operation
null of JS, if entered into the operation, will really be resolved to 0 or false:
(1 + null) # 1 (1 * null) # 0 (1 * null) # Infinity
undefined enters into the operation, and law 1 gives NaN:
(1 + undefined) # NaN (1 * undefined) # NaN (1 / undefined) # NaN
logic
Both null and undefined are considered false when judged logically.
Using only one judgment, it is possible to check whether both of these terms are true:
// Will the false, -0, +0, NaN with '' Think of it as null.
if (v) {
// v Have a value
} else {
// v There is no value
}
But if you hit the pit ==
var foo;
console.log(foo == null); // true
console.log(foo == undefined); // true
console.log(foo === null); // false
console.log(foo === undefined); // true
console.log(null == undefined); // true
Good practice, 1 law USES ===
Determine that a quantity is defined and not empty, using only: if (a! == null
&
&
a ! = = undefined).
= = = = =
1.== is used to determine whether two values are equal
When two value types are not the same, an automatic conversion occurs, and the result is very counter-intuitive, which may not be what you want.
"" == "0" // false
0 == "" // true
0 == "0" // true
false == "false" // false
false == "0" // true
false == undefined // false
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, === returns true,! == return false." -- JavaScript: The Essence of Language
Best practices:
Whenever you use === and in comparison operations! = =
json operation
var person = {name :'Saad', age : 26, department : {ID : 15, name : "R&D"} };
var stringFromPerson = JSON.stringify(person);
/* stringFromPerson is equal to "{"name":"Saad","age":26,"department":{"ID":15,"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!
});
As well as
var f = function foo(){
return typeof foo; // foo It's valid within the internal scope
};
// foo Used externally is not visible
typeof foo; // "undefined"
f(); // "function"
Anonymous functions
> function id(x) { return x }
> id()
undefined
a = 1;
a !== undefined // true
a = undefined
var b
a === b //true
0
Best practices
1. When defining multiple variables, omit the var keyword and replace it with a comma
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, don't omit semicolons, and don't omit curly braces
Omitting the semicolon can lead to bigger, unknown, hard-to-find problems
> function id(x) { return x }
> id()
undefined
a = 1;
a !== undefined // true
a = undefined
var b
a === b //true
3
A better way
> function id(x) { return x }
> id()
undefined
a = 1;
a !== undefined // true
a = undefined
var b
a === b //true
4
3. Use {} instead of new Ojbect()
There are several ways to create objects in JavaScript. Perhaps the traditional approach is to use the "new" plus constructor, as follows:
> function id(x) { return x }
> id()
undefined
a = 1;
a !== undefined // true
a = undefined
var b
a === b //true
5
A better way
> function id(x) { return x }
> id()
undefined
a = 1;
a !== undefined // true
a = undefined
var b
a === b //true
6
var o = {
name: 'Jeffrey',
lastName = 'Way',
someFunction : function() {
console.log(this.name);
}
};
Simply grouping multiple global variables in one namespace would significantly reduce the likelihood of bad interactions with other applications, components, or class libraries. - Douglas Crockford
4. Use [] instead of new Array()
var a = new Array();
a[0] = "Joe";
a[1] = 'Plumber';
A better approach:
> function id(x) { return x }
> id()
undefined
a = 1;
a !== undefined // true
a = undefined
var b
a === b //true
9
5. typeof judgment
typeof1 sort can only be returned the following results: number, boolean, string, function, object, undefined
expr:
typeof xx === ''
typeof xx !== ''
e.g.
// Numbers
typeof 37 === 'number';
typeof 3.14 === 'number';
typeof Infinity === 'number';
typeof NaN === 'number'; // although NaN is "Not-A-Number" The abbreviation of , mean " not 1 A digital "
// Strings
typeof "" === 'string';
typeof "bla" === 'string';
typeof (typeof 1) === 'string'; // typeof The return must be 1 A string
// Booleans
typeof true === 'boolean';
typeof false === 'boolean';
// Undefined
typeof undefined === 'undefined';
typeof blabla === 'undefined'; // 1 Undefined variables , or 1 A defined variable with no initial value assigned
// Objects
typeof {a:1} === 'object';
typeof [1, 2, 4] === 'object'; // use Array.isArray or Object.prototype.toString.call The method can tell 1 Arrays and real objects
typeof new Date() === 'object';
// Functions
typeof function(){} === 'function';
typeof Math.sin === 'function';
typeof null === 'object'; // from JavaScript Since the birth of ,1 It's straight up like that .
6.3 Meta operators: Powerful and sexy
grammar
expression ? xxx : yyy
bad
var direction;
if(x < 200){
direction = 1;
} else {
direction = -1;
}
good
var direction = x < 200 ? 1 : -1;
7. Use logical AND/OR to make conditional judgments
var foo = 10;
foo == 10 && doSomething(); // Is equivalent to if (foo == 10) doSomething();
foo == 5 || doSomething(); // Is equivalent to if (foo != 5) doSomething();
// The default value
a = b || 'default'
return b || c || d > 1 ? 0 : 2
8. Don't forget to use the var keyword when assigning a variable
Assigning a value to an undefined variable causes a global variable to be created. Avoid global variables
9. Self-calling functions
Call an anonymous function (ES165en-ES166en Anonymous Function) or call a function expression (ES169en-ES170en Invoked Function Expression) on the spot. This is a function that is automatically executed immediately after creation
(function(){
// some private code that will be executed automatically
})();
(function(a,b){
var result = a+b;
return result;
})(10,20)
10. Avoid eval() and Function constructors
Eval= evil, which not only significantly reduces the performance of the script, but also poses a significant security risk by paying too much permission to the text to be executed and avoiding it
Using the eval and Function constructors is a very expensive operation because each time they call the script engine to convert the source code into executable code.
var func1 = new Function(functionCode);
var func2 = eval(functionCode);
11. Avoid with()
Using with() inserts a global variable. Therefore, a variable with the same name can be overwritten and cause unnecessary trouble
The script is placed at the bottom of the page
Remember - the primary goal is to get the page to the user as quickly as possible, the script is blocked, and the browser cannot continue rendering until the script has been loaded and executed. As a result, users will be forced to wait longer
13. Avoid declaring variables within For statements
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 += 'my number: ' + i;
console.log(i);
}
14. Add comments to code
// Loop through the array, printing each item's name. .
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 of a particular type
var oStringObject = new String("hello world");
console.log(oStringObject instanceof String); // The output "true"
// judge foo Whether it is Foo Instances of the class
function Foo(){}
var foo = new Foo();
console.log(foo instanceof Foo)//true
// judge foo Whether it is Foo Instances of the class , And is an instance of its parent type
function Aoo(){}
function Foo(){}
Foo.prototype = new Aoo();//JavaScript Prototype inheritance
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
The ES228en. apply(obj,args) method accepts two parameters
obj: This object will replace the this object in the Function class
args: This is the array that will be passed to Function (args--) as an argument
>
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 to use depends on the type of parameter