The fifth chapter Reference type
One 、Object
1、 establish :
- new Operator followed by Object Constructors
var person = new Object();
person.name = "Nicholas";
Copy code
- Object literal
var person = {
name : "Nicholas"
};
var person = {}; // And new Object() identical
person.name = "Nicholas";
Copy code
Object literals are also the preferred way to pass a large number of optional parameters to a function
function displayInfo(args) {
var output = "";
if (typeof args.name == "string"){
output += "Name: " + args.name + "\n";
}
if (typeof args.age == "number") {
output += "Age: " + args.age + "\n";
}
}
displayInfo({
name: "Nicholas",
age: 29
});
Copy code
2、 visit
- Dot notation
alert(person.name);
Copy code
- Square brackets mean :
Can pass Variable
To access properties ; The attribute name can contain Non alphanumeric
Of , Using dot notation will make mistakes ; The attribute name is Keywords or reserved words
, Using dot notation will make mistakes , You can also use square brackets .
alert(person["name"]);
var propertyName = "name";
alert(person[propertyName])
alert(person["first name"]);
Copy code
Two 、Array
ECMAScript Each item of the array can hold any type of data , The size of the array can be adjusted dynamically , That is, it can grow automatically as data is added to accommodate new data .
1、 establish :
- Array Constructors
var colors = new Array();
var colors = new Array(20);// Appoint length attribute
var colors = new Array("Greg"); // Delivery contains 1 term ( When a value is numeric , As length; Otherwise, it is treated as an array item )
var colors = new Array("red", "blue", "green");// Pass the contained items
var colors = Array(3);// It can be omitted new The operator
Copy code
- Array literal :
Represented by a pair of square brackets containing array items , Multiple array items are separated by commas
var colors = ["red", "blue", "green"]; // Create a containing 3 An array of strings
var names = []; // Create an empty array
Copy code
2、 visit
Square brackets and provide corresponding values based on 0 Digital index of
var colors = ["red", "blue", "green"]; // Define an array of strings
alert(colors[0]); // Show first item
colors[2] = "black"; // Revise the third item
colors[3] = "brown"; // Add a fourth item
Copy code
3、length
By setting this property , You can remove items from the end of the array or add new items to the array
var colors = ["red", "blue", "green"];
// remove
colors.length = 2;
alert(colors[2]); //undefined
// add to
colors.length = 4;
alert(colors[3]); //undefined
Copy code
4、 Transformation method
All objects have toLocaleString()、toString() and valueOf() Method .
- toString(): Returns a comma separated string concatenated by the string form of each value in the array ;
- valueOf(): Return or array ; actually , In order to create this string, we will call each item of the array toString() Fang
Law .
- join(): Use different delimiters to construct this string ;
5、 Stack method ( Last in, first out )
- push(): Receive any number of parameters , Add them to the end of the array one by one , And return the length of the modified array ;
- pop(): Remove the last entry from the end of the array , Reduce the length value , Then return the removed item .
6、 Queue method ( Last in, first out )
-
push()
-
shift(): Removes the first item in the array and returns it , At the same time, reduce the array length by 1.
-
unshift(): Add any item to the front of the array and return the length of the new array ;
-
pop()
7、 Reorder method
- reverse(): reverse
- sort(): By default ,sort() Method to arrange array items in ascending order .sort() Method will call the toString() Transformation method , Then compare the resulting string .
var values = [0, 1, 5, 10, 15];
values.sort();
alert(values); //0,1,10,15,5
Copy code
After transformation , Compare strings , It does not satisfy the sorting of values . therefore sort() Method can take a comparison function as an argument , So that we can specify which value precedes which value .
function compare(value1, value2) {
if (value1 < value2) {// Returns a negative number if the first parameter should precede the second
return -1;
} else if (value1 > value2) {// Returns a positive number if the first parameter should be after the second
return 1;
} else {// Return if two parameters are equal 0
return 0;
}
}
function compare(value1, value2){// Ascending
return value2 - value1;
}
var values = [0, 1, 5, 10, 15];
values.sort(compare);
alert(values); //0,1,5,10,15
Copy code
8、 Operation method
- concat(): First create a copy of the current array , Then add the received parameters to the end of the copy one by one , Finally, return the newly constructed array .
Does not affect the original array
- slice(): Accept one or two parameters , That is, to return the start and end positions of the item . With only one parameter ,slice() Method to return from the
Parameter to specify all items starting at the end of the current array . If you have two parameters , This method returns the item between the start and end positions , But it doesn't include the end position . Does not affect the original array
- splice(): Delete (2 Parameters , The location of the first item to delete and the number of items to delete ); Insert (3 Parameters : The starting position 、0 Number of items to delete 、 Any number of items to insert ); Replace (3 Parameters : The starting position 、 Number of items to delete 、 Any number of items to insert ).
Returns the item removed from the original array ( Array )
9、 Location method
Receive two parameters : The item to find 、( Optional ) Index indicating the location of the search start point ; Returns the position of the searched item in the array , Return if not found -1.
- indexOf(): Look backward from the beginning of the array
- lastIndexOf(): Start at the end of the array and look forward
10、 Iterative method
Receive two parameters : Functions to run on each item 、( Optional ) Scope object to run this function —— influence this Value . The parameter function has three parameters : Value of array item 、 The position of the item in the array 、 Array object itself . Does not affect the original array
- every(): Run the given function for each item in the array , If the function returns... For each item true, Then return to true.( Boolean value )
- some(): Run the given function for each item in the array , If the function returns true, Then return to true.( Boolean value )
- filter(): Run the given function for each item in the array , Return this function will return true Array of items from .( Array )
- forEach(): Run the given function for each item in the array .( No return )
- map(): Run the given function for each item in the array , Returns an array of the results of each function call .( Array )
var numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
var everyResult = numbers.every(function (item, index, array) {
return (item > 2);
});
alert(everyResult); //false
var someResult = numbers.some(function (item, index, array) {
return (item > 2);
});
alert(someResult); //true
var filterResult = numbers.filter(function (item, index, array) {
return (item > 2);
});
alert(filterResult); //[3,4,5,4,3]
var mapResult = numbers.map(function (item, index, array) {
return item * 2;
});
alert(mapResult); //[2,4,6,8,10,8,6,4,2]
numbers.forEach(function (item, index, array) {
// Do something
});
Copy code
11、 Merging method
Iterate over all items of the array , Then build a final return value . Receive two parameters : A function called in each item 、( Optional ) Initial value as the basis of consolidation . The parameter function receives 4 Parameters : Previous value 、 Current value 、 Index and array objects for items ; Any value returned by the function is automatically passed to the next item as the first parameter . The first iteration occurs on the second term of the array , So the first argument is the first item in the array , The second parameter is the second term of the array .
- reduce(): Start with the first item in the array
- reduceRight(): From the last item of the array
var values = [1, 2, 3, 4, 5];
var sum = values.reduce(function (prev, cur, index, array) {
return prev + cur;
});
alert(sum); //15
Copy code