Javascript Precautions

Operation

&&Operation with operation, only if all are true, &&the operation result is true:

to true && to true ; // this && statement evaluates to true 
to true && false ; // result of this calculation && statement is false 
false && to true && false ; // This statement is false && results

 

||A calculation or operation, as long as one is true, ||the operation result is true:

false || false ; // this || statement evaluates to false 
true || false ; // result of this calculation || statement is true 
false || true || false ; // this statement is true results ||

 

Compare

When we compare to Number, you can get a Boolean value by comparison operators:

2 > 5; // false
5 >= 2; // true
7 == 7; // true

In fact, JavaScript allows any data type for comparison:

false == 0; // true 
false === 0; // false

 

Special attention should be equal operator ==. JavaScript in the design, there are two comparison operators:

The first is a ==comparison, it is automatically converted and then compare the data type, very often, the result will be a very strange;

The second is ===the comparison, it does not automatically convert data types, data types if not, return false, if consistent, then compare.

Since this design flaw JavaScript, do not use ==comparisons, always stick with ===the comparison.

Another exception is NaNthe special Number values are not equal with all other, including its own:

=== NaN NaN; // false

The only determination NaNprocess by isNaN()the function:

isNaN (NaN); // true

 

Finally, note that floating point numbers are equal comparison:

1 / 3 === (1 - 2 / 3); // false

 

This is not a design flaw JavaScript. In floating-point arithmetic process will produce an error, because the computer can not accurately represent infinite decimal. To compare floating point numbers are equal, only calculates an absolute value of a difference between them, to see if less than a certain threshold value:

Math.abs(1 / 3 - (1 - 2 / 3)) < 0.0000001; // true

 

 

null和undefined

nullIt represents a "null" value, and it 0and the empty string ''different, 0is a numerical value, ''represents the length of a string of 0's, and nullrepresents a "blank."

In other languages, has a similar JavaScript is nullexpressed, for example, also use Java null, Swift with nil, Python with Nonerepresentation. However, in JavaScript, and there is a nullsimilar undefined, which indicates "undefined."

JavaScript designers hope to use nullrepresents an empty value , and undefinedrepresents the value undefined . This proved not use any eggs , not meaningful distinction between the two. In most cases, we should use null. undefinedOnly useful if the function parameter is determined whether passed .

 

 

Another method is to create an array by Array()function to achieve:

new new the Array (1, 2, 3); // creates an array [1, 2, 3]

 

Objects

JavaScript is a group of objects from the key - the value of the set consisting of the disorder, for example:

var person = {
    name: 'Bob',
    age: 20,
    tags: ['js', 'web', 'mobile'],
    city: 'Beijing',
    hasCar: true,
    zipcode: null
};

 

JavaScript object key is a string type, the value can be any data type.

The above-described personobjects has defined six key-value pairs, where each key property of an object is also known, for example, personthe nameattribute 'Bob', zipcodeproperty null.

To obtain the properties of an object, we use 对象变量.属性名way:

 
person.name; // 'Bob'
person.zipcode; // null

 

strict mode

JavaScript in the beginning of the design, in order to facilitate beginners to learn, not mandatory with vardeclare variables. This design errors brought serious consequences: If you do not pass a variable varwas declared use, then the variables are automatically declared as global variables:

No varvariable declared will be treated as a global variable, in order to avoid this pitfall, all the JavaScript code should use strict mode. JavaScript code we've written in the back will all use strict mode.

 

Array

The JavaScript Arraycan contain any type of data, and access each element by index.

 

Please note directly to Arraythe lengthnew values assigned will lead to Arraychange in size:

var arr = [1, 2, 3];
arr.length; // 3
arr.length = 6;
arr; // arr变为[1, 2, 3, undefined, undefined, undefined]
arr.length = 2;
arr; // arr变为[1, 2]

 

Please note that if the assignment by the index, the index exceeds the range, it will also cause Arraychanges in the size:

var arr = [1, 2, 3];
arr[5] = 'x';
arr; // arr变为[1, 2, 3, undefined, undefined, 'x']

 

Objects

JavaScript is a collection of data objects of a disordered type, which consists of a number of key-value pairs.

JavaScript object used to describe an object in the real world. For example, to describe "Bob" naughty children, we can use a number of key-value pairs to describe him:

var xiaoming = {
    name: '小明',
    birth: 1990,
    school: 'No.1 Middle School',
    height: 1.70,
    weight: 65,
    score: null
};

 

Finally, at the end of a key-value pair you do not need to add ,, if added, some browsers (such as a low version of IE) will report an error.

 

Access to property is via .operator to complete, but this requires the attribute name must be a valid variable name. If the attribute name contains special characters, you must ''enclose:

var xiaohong = {
    name: '小红',
    'middle-school': 'No.1 Middle School'
};

xiaohongThe property name middle-schoolis not a valid variable, we need to use ''quotes. This property can not be used to access .operator, must ['xxx']be accessed:

 

 

If you visit a nonexistent property will return to what it? JavaScript provides access to non-existent property is not an error, but instead returns undefined:

 

If we want to detect    xiaoming whether it has a property, you can use   in the operator:

var xiaoming = {
    name: '小明',
    birth: 1990,
    school: 'No.1 Middle School',
    height: 1.70,
    weight: 65,
    score: null
};
'name' in xiaoming; // true
'grade' in xiaoming; // false

 

 

But be careful, if you injudge a property is present, this is not necessarily the property xiaoming, it may be xiaominginherited in:

'toString' in xiaoming; // true

As toStringdefined in the objectobject, and all objects will eventually point on the prototype chain object, it xiaomingalso has toStringproperties.

To determine whether a property is xiaomingtheir own, not inherited, you can use hasOwnProperty()the method:

var xiaoming = {
    name: '小明'
};
xiaoming.hasOwnProperty('name'); // true
xiaoming.hasOwnProperty('toString'); // false

 

Conditional

The JavaScript null, undefined, 0, NaNand the empty string ''considered false, be treated as a value other true, so the above determination condition codes result true.

 

 

 

 

cycle

 

 

var x = 0;
var i;
for (i=1; i<=10000; i++) {
    x = x + i;
}
x; // 50005000

 

 

Let us analyze the forcontrol loop conditions:

 

  • i = 1 This is the initial condition, the variable i is set to 1;
  • i <= 10000 This is a determination condition is satisfied cycle continues, does not satisfy the loop exits;
  • i ++ which is incremented after each cycle conditions, because after each loop variable i are incremented by 1, so that eventually, after several cycles does not satisfy the determination condition i<=10000and the loop is exited.

 

 

 

forThe most common local loop using an index to traverse an array:

 

var arr = ['Apple', 'Google', 'Microsoft'];
var i, x;
for (i=0; i<arr.length; i++) {
    x = arr[i];
    console.log(x);
}

 

forCycle of three conditions is may be omitted if there is no exit conditions determine the cycle, you must use the breakstatement to exit the loop, otherwise infinite loop:

var X = 0 ;
 for (;;) { // the infinite loop 
    if (X> 100 ) {
         BREAK ; // to exit the loop by determining if 
    } 
    X ++ ; 
}

 

 

for ... in

forCycle is a variant for ... incycle, it can put all the attributes of an object are cyclically out:

var o = {
    name: 'Jack',
    age: 20,
    city: 'Beijing'
};
for (var key in o) {
    console.log(key); // 'name', 'age', 'city'
}

 

 

To filter out objects inherit property, use hasOwnProperty()to achieve:

 

var o = {
    name: 'Jack',
    age: 20,
    city: 'Beijing'
};
for (var key in o) {
    if (o.hasOwnProperty(key)) {
        console.log(key); // 'name', 'age', 'city'
    }
}

 

 

Because Arrayalso the object and its index of each element is considered property of the object, so that for ... inthe cycle can be recycled directly out Arrayof the index:

var a = ['A', 'B', 'C'];
for (var i in a) {
    console.log(i); // '0', '1', '2'
    console.log(a[i]); // 'A', 'B', 'C'

Please note that for ... infor Arraythe cycle is obtained Stringinstead Number.

 

 

while

forCirculates useful when a known loop start and end conditions . While ignoring the conditions of the above forcycle is easy to see the logic loop, this time with a whilecycle better.

whileOnly a judge loop condition, the condition is satisfied, the continuous loop , the loop exits when the condition is not satisfied. For example, we want to calculate the sum of all odd-numbered less than 100, can be achieved using a while loop:

 

 

do ... while

The last cycle is a  do { ... } while() cycle, and it is whilethe only difference is that the cycle, not the determination condition at the time of the start of each cycle, but the cycle is completed each time the judgment condition :

var n = 0;
do {
    n = n + 1;
} while (n < 100);
n; // 100

 

With a  do { ... } while() circulation Be careful execution cycle experience at least once, while forand whilecycle time may not execute.

 

 

Map and Set

 

MapIs a set of structural key-value pairs, with a fast search speed.

 

 

 

For example, suppose you want to find the corresponding results of the students by name, if Arrayrealized, it requires two Array:

 

var names = ['Michael', 'Bob', 'Tracy'];
var scores = [95, 75, 85];

 

Given a name, to find the corresponding results, you must first find the location corresponding to the names in, then remove the corresponding results from the scores, the longer the Array, it takes longer .

 

 

If Map implementation, only a "name" - "accomplishments" of the table, find the names directly from the results, no matter how big the table, the search speed will not slow down . Write a Map with JavaScript as follows:

 

var m = new Map([['Michael', 95], ['Bob', 75], ['Tracy', 85]]);
m.get('Michael'); // 95

 

 

 

Initialization Maprequires a two-dimensional array, or simply initialize a blank Map. MapIt has the following methods:

 

var m = new new the Map (); // empty the Map 
m.set ( 'Adam', 67); // Add a new value-Key 
m.set ( 'Bob', 59 ); 
m.has ( 'Adam') ; // if there is Key 'Adam': to true 
m.get ( 'Adam'); // 67 
. m the delete ( 'Adam'); // delete Key 'Adam' 
m.get ( 'Adam'); // undefined

 

 

Since only a key corresponding to a value, therefore, for a plurality of times into the value key, the preceding value will later washed away:

 

var m = new Map();
m.set('Adam', 67);
m.set('Adam', 88);
m.get('Adam'); // 88

 

Set

SetAnd Mapsimilarly, the set is a set of key , but not stored value . Since the key can not be repeated, so that , in the Setmiddle, no duplicate key .

 

To create a Setneed to provide a Arrayas an input, or simply create an empty Set:

var S1 = new new the Set (); // empty the Set 
var S2 = new new the Set ([1, 2, 3]); // containing 1, 2, 3

 

Repeated elements Setautomatically filtering:

var s = new Set([1, 2, 3, 3, '3']);
s; // Set {1, 2, 3, "3"}

 

By add(key)may be added to the method elements Setmay be repeated to add, but has no effect:

s.add (. 4 ); 
S; // Set {1, 2, 3, 4} 
s.add (. 4 ); 
S; // still Set {1, 2, 3, 4}

 

By delete(key)can remove elements method:

var s = new Set([1, 2, 3]);
s; // Set {1, 2, 3}
s.delete(3);
s; // Set {1, 2}

 

MapAnd Setis ES6 standard new data types, decide if you want to use is based on browser support.

Guess you like

Origin www.cnblogs.com/Rivend/p/12084686.html