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 NaN
the special Number values are not equal with all other, including its own:
=== NaN NaN; // false
The only determination NaN
process 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
null
It represents a "null" value, and it 0
and the empty string ''
different, 0
is a numerical value, ''
represents the length of a string of 0's, and null
represents a "blank."
In other languages, has a similar JavaScript is null
expressed, for example, also use Java null
, Swift with nil
, Python with None
representation. However, in JavaScript, and there is a null
similar undefined
, which indicates "undefined."
JavaScript designers hope to use null
represents an empty value , and undefined
represents the value undefined . This proved not use any eggs , not meaningful distinction between the two. In most cases, we should use null
. undefined
Only 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 person
objects has defined six key-value pairs, where each key property of an object is also known, for example, person
the name
attribute 'Bob'
, zipcode
property 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 var
declare variables. This design errors brought serious consequences: If you do not pass a variable var
was declared use, then the variables are automatically declared as global variables:
No var
variable 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 Array
can contain any type of data, and access each element by index.
Please note directly to Array
the length
new values assigned will lead to Array
change 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 Array
changes 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' };
xiaohong
The property name middle-school
is 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 in
judge a property is present, this is not necessarily the property xiaoming
, it may be xiaoming
inherited in:
'toString' in xiaoming; // true
As toString
defined in the object
object, and all objects will eventually point on the prototype chain object
, it xiaoming
also has toString
properties.
To determine whether a property is xiaoming
their 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
, NaN
and 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 for
control 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<=10000
and the loop is exited.
for
The 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); }
for
Cycle of three conditions is may be omitted if there is no exit conditions determine the cycle, you must use the break
statement 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
for
Cycle is a variant for ... in
cycle, 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 Array
also the object and its index of each element is considered property of the object, so that for ... in
the cycle can be recycled directly out Array
of 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 ... in
for Array
the cycle is obtained String
instead Number
.
while
for
Circulates useful when a known loop start and end conditions . While ignoring the conditions of the above for
cycle is easy to see the logic loop, this time with a while
cycle better.
while
Only 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 while
the 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 for
and while
cycle time may not execute.
Map and Set
Map
Is 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 Array
realized, 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 Map
requires a two-dimensional array, or simply initialize a blank Map
. Map
It 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
Set
And Map
similarly, the set is a set of key , but not stored value . Since the key can not be repeated, so that , in the Set
middle, no duplicate key .
To create a Set
need to provide a Array
as 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 Set
automatically 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 Set
may 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}
Map
And Set
is ES6 standard new data types, decide if you want to use is based on browser support.