Javascript system, Array object learning notes, array learning notes
An array is a set of values in order. The attribute names of objects are unordered. In essence, arrays use numbers as search keys, and objects have custom attribute names. Javascript does not actually associate arrays, but objects can be used to implement Association functions.
Array () is only a special type of Object (). That is to say, an Array () instance is basically an Object () instance with some additional functions. An array can store any type of values. These values can be updated or deleted at any time, and the array size is dynamically adjusted.
I. Create an array
Like most objects in Javascript, you can use the new operator together with the Array () constructor, or use the literal syntax to create an Array object.
[1] using the Array Constructor (when using the Array constructor, you can also omit the New operator), you can pass the values of the Array instance to the constructor, separated by commas as parameters, the Array () constructor can receive 4294967295 (about 4.3 billion) parameters.
If there is only one parameter: If a value is passed, it is used to set the length of the array. If other types of parameters are passed, only one array containing the value is created.
var colors;
console.log(colors = new Array(),colors.length);//[] 0
console.log(colors = new Array('red','blue','green'),colors.length);//['red','blue','green'] 3
console.log(colors = new Array(20),colors.length);//[] 20
console.log(colors = new Array('red'),colors.length);//['red'] 1
var foo = new Array(1,2,3);
var bar = new Array(100);
console.log(foo[0],foo[2]);//1 3
console.log(bar[0],bar.length);//undefined 100
[2] array literal representation
var colors = ['red', 'blue', 'green'];
var colors = [];
// Array constructor
var myArray1 = new Array ('blue', 'green', 'orange', 'red');
console.log (myArray1); // ['blue', 'green', 'orange', 'red']
// Array literal representation
var myArray2 = ['blue', 'green', 'orange', 'red'];
console.log (myArray2); // ['blue', 'green', 'orange', 'red']
var colors = [1,2,];
// In IE8 and before, there will be an array of three items, each of which is 1, 2 and undefined. Arrays in other browsers containing only 1 and 2
var colors = [,,,];
// An array of 4 items will be created in IE8 and before, and an array of 3 items will be created in other browsers
2. Array Operations
When reading and setting the array value, square brackets should be used and a 0-based numeric index should be provided for the corresponding value.
The length attribute of the array indicates the number of values in the array, while the numeric index of the array starts from 0. The length attribute is readable and writable. By setting the Length attribute of the array, you can remove items from the end of the array or add new items to the array. If the set length is greater than the actual number of values in the array, the undefined value is added to the array. If the number of length values is set to less than the number of values in the array, the values in the array may be deleted.
var myArray = ['blue','green','orange','red'];
console.log(myArray.length);//4
myArray.length = 99;
console.log(myArray.length);//99
myArray.length = 1;
console.log(myArray[1]);//undefined
console.log(myArray);//['blue']
var colors = ['red','blue','green'];
colors.length = 2;
alert(colors[2]);//undefined
colors.length = 4;
alert(colors[3]);//undefined
When a value is placed above the array size, the array recalculates its length value, that is, the length value equals to the last index plus 1, javascript will use the undefined value to fill all indexes before the current index
var myArray = [];
myArray[50] = 'blue';
console.log(myArray.length);//51
var colors = ['red','blue','green'];
colors[99] = 'black';
console.log(colors.length);//100
[Tips] using the length attribute, you can easily add new items to the end of the array.
Colors [colors. length] = 'black ';
Iii. inherited methods
ToString ()
Returns a comma-separated string consisting of strings of each value in the array.
Valueof ()
Returns an array.
var colors = ['red', 'blue', 'green'];
console.log (colors.valueOf ()); // ['red', 'blue', 'green']
alert (colors.valueOf ()); // 'red, blue, green'
alert (colors.toString ()); // 'red, blue, green'
alert (colors); // 'red, blue, green' [Note] Since alert () is receiving string parameters, it will call the toString () method in the background and will get the same result as the toString () method
ToLocaleString ()
When this method is called, each value of the array calls the toLocaleString () method.
var person1 = {
toLocaleString: function(){
return 'Nikolaos';
},
toString: function(){
return 'Nicholas';
}
};
var person2 = {
toLocaleString: function(){
return 'Grigorios';
},
toString: function(){
return 'Greg';
}
};
var people = [person1,person2];
alert(people);//Nicholas,Greg
alert(people.toString());//Nicholas,Greg
alert(people.toLocaleString());//Nikolaos,Grigorios
Iv. instance method
Array Conversion
Join ()
The toLocaleString (), toString (), and valueOf () methods inherited by arrays return array items by default in the form of comma-separated characters; while join () the join () method can use different delimiters to construct this string. The join () method only receives one parameter and serves as a separator string, and then returns a string containing all array items. If you do not input any value to the join () method or undefined, use a comma as the separator.
var colors = ['red', 'green', 'blue'];
console.log (colors.join (',')); // 'red, green, blue'
console.log (colors.join ('||')); / '' || green || blue '
console.log (colors.join ()); // 'red, green, blue'
console.log (colors.join (undefined)); // 'red, green, blue' [Note] IE7- will use undefined as a separator
[Note] if the value of an item in the array is null or undefined, the value is expressed as an empty string in the results returned by the join (), toLocaleString (), toString (), and valueOf () methods.
Array Detection
Since ES3 made the rule, there has been a classic problem of determining whether an object is an array. The common method is to use the instance operator, but this method has its limitations. ES5 specifically adds the isArray () method to detect arrays.
var value = [123];
console.log(value instanceof Array);//true
The problem with the instanceof operator is that it assumes that there is only one global execution environment. If the webpage contains multiple frameworks, there are actually two or more different global environments, as a result, there are two or more arrays of different versions. If an array is imported from one framework to another, the input array and the array originally created in the second framework have different constructors respectively.
// Cannot share prototype property in different frameworks
var iframe = document.createElement ('iframe');
document.body.appendChild (iframe);
var value = new window.frames [0] .Array;
console.log (value instanceof Array); // false
console.log (value.constructor == Array); // false
However, the toString () method can be called across prototype chains in different frameworks.
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
var value = new window.frames[0].Array;
console.log(Object.prototype.toString.call(value));//[object Array]
ES5 adds the Array. isArray () method to determine whether a value is an Array or not.
Array. isArray ()
var value = [123];
console.log(Array.isArray(value));//true
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
var value = new window.frames[0].Array;
console.log(Array.isArray(value));//true
Stack and queue
Push ()
You can 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 of the array, and return the removed entry.
Shift ()
Remove the first entry from the array and return the item. At the same time, the length of the array is reduced by 1 (combined with shift () and push () to simulate the queue)
Unshift ()
Add any entry at the front end of the array and return the length of the new array (use unshift () and pop () to simulate the queue in the opposite direction)
[Note] IE7-the browser's unshift () method always returns undefined
var colors = [];
var count = colors.push('red','green');
console.log(colors,count);//['red','green'] 2
var count = colors.pop();
console.log(colors,count);//['red'] 'green'
var count = colors.unshift('white','black');
console.log(colors,count);//["white", "black", "red"] 3
var count = colors.shift();
console.log(colors,count);//["black", "red"] "white"
Sorting Method
Reverse ()
Returns the sorted array. The original array order also changes.
var array = [1,2,4,3,5];
console.log(array,array.reverse());//[5,3,4,2,1] [5,3,4,2,1]
var array = ['str',true,3];
console.log(array,array.reverse());//[3,true,'str'] [3,true,'str']
Sort ()
By default, array items are arranged in ascending order of strings. The sort method calls the toString () method of each array item, sorts the obtained strings, and returns the sorted array, the order of the original array also changes.
var array = [1,2,4,3,5];
console.log(array,array.sort());//[1,2,3,4,5] [1,2,3,4,5]
var array = ['3str',3,2,'2'];
console.log(array,array.sort());//[2, "2", 3, "3str"] [2, "2", 3, "3str"]
var array = [1,5,10,50];
console.log(array,array.sort());//[1, 10, 5, 50] [1, 10, 5, 50]
[Note] the sort () method can take a comparison function as a parameter to specify the value before which. The comparison function receives two parameters. If the first parameter is located before the second parameter, a negative number is returned. If the two parameters are equal, 0 is returned, if the first parameter is located after the second parameter, a positive number is returned.
[Tips] comparison functions
function compare (value1, value2) {
if (value1 <value2) {
return -1;
} else if (value1> value2) {
return 1;
} else {
return 0;
}
}
var array = ['5px', 50,1,10];
// When the number is compared with the string, the string '5px' will be converted to NaN, so the result is false
console.log (array.sort (compare)); // ["5px", 1, 10, 50]
The value type or valueOf () method returns the object type of the value type. The comparison function can be simplified:
function compare(value1,value2){
return value1 - value2;
}
var array = ['5px',50,1,10];
console.log(array.sort(compare));//["5px",1,10,50]
var array = [5,50,1,10];
console.log(array.sort(compare));//[1,5,10,50]
[Tips] Create a random array
function compare(){
return Math.random() - 0.5;
}
var array = [1,2,3,4,5];
console.log(array.sort(compare));//[2,1,5,4,3]
Procedure
Concat ()
Create a new array based on all items in the current array. first create a copy of the current array, and then add the received parameters to the end of the copy, finally, the newly constructed array (concat () does not affect the original array) is returned)
If you do not pass a parameter to the concat () method, it only copies the current array. If the parameter is one or more arrays, this method adds each item in these arrays to the result array. If the passed value is not an array, these values are simply added to the end of the result array.
var numbers = [1,2];
console.log(numbers,numbers.concat());//[1,2] [1,2]
console.log(numbers,numbers.concat([5,4,3],[3,4,5],1,2));//[1,2] [1,2,5,4,3,3,4,5,1,2]
Slice ()
Creates a new array based on one or more items in the current array and accepts one or two parameters, that is, the start and end positions of the items to be returned, and finally returns the new array (slice () does not affect the original array)
If there is no parameter, the original array is returned. If there is only one parameter, the slice () method returns all items starting from the specified position of the parameter to the end of the current array. If there are two parameters, this method returns the entry between the start position and the end position, but does not include the entry at the end position. If the parameter is a negative number, the array Length plus a negative number is used as the parameter; if the end position is less than the start position, an empty array is returned.
var numbers = [1,2,3,4,5];
console.log(numbers.slice());//[1,2,3,4,5]
console.log(numbers.slice(2));//[3,4,5]
console.log(numbers.slice(2,3));//[3]
console.log(numbers.slice(-3));//-3+5=2 -> [3,4,5]
console.log(numbers.slice(2,1));//[]
Splice ()
The original array is changed to the modified array, and splice () returns an array composed of items deleted from the original array. If no items are deleted, an empty array is returned. If the first parameter is a negative number, the array Length plus a negative number is used as the parameter. If the second parameter is a negative number, 0 is used as the parameter.
[1] Delete: the two parameters are the location of the first item to be deleted and the number of items to be deleted.
[2] Insert: the three parameters are start position, 0 (base number to be deleted), and the items to be inserted.
[3] replacement: the three parameters are the starting position, number of items to be deleted, and items to be inserted.
var numbers = [1,2,3,4,5];
console.log(numbers.splice(),numbers);//[] [1, 2, 3, 4, 5]
console.log(numbers.splice(0,2),numbers);//[1,2] [3,4,5]
var numbers = [1,2,3,4,5];
console.log(numbers.splice(1,0,11,12),numbers);//[] [1,11,12,2,3,4,5]
var numbers = [1,2,3,4,5];
console.log(numbers.splice(1,3,11,12),numbers);//[2,3,4] [1,11,12,5]
var numbers = [1,2,3,4,5];
console.log(numbers.splice(-4,3,11,12),numbers);//-4+5=1 -> [2,3,4] [1,11,12,5]
var numbers = [1,2,3,4,5];
console.log(numbers.splice(-4,-3,11,12),numbers);//-4+5=1 -> [] [1,11,12,2,3,4,5]
Location Method
ES5 adds two Location Methods indexOf () and lastIndexOf () to the array instance (). Both methods receive two parameters: the item to be searched and the index indicating the start position (optional ). Returns the position of the first search item that meets the condition in the array. If no position is found,-1 is returned (the position method does not affect the original array)
[Note] when comparing parameters, the method uses full equal operators.
IndexOf () search from front to back
LastIndexOf () from back to forward
var numbers = [1,2,3,4,5,4,3,2,1];
console.log (numbers.indexOf (4)); // 3
console.log (numbers.lastIndexOf (4)); // 5
console.log (numbers.indexOf (4,4)); // 5
console.log (numbers.lastIndexOf (4,4)); // 3
var person = {name: 'Nicholas'};
var people = [{name: 'Nicholas'}];
var morePeople = [person];
alert (people.indexOf (person)); //-1, because person and people [0] have the same value, but are two references
alert (morePeople.indexOf (person)); // 0, because person and morepeople [0] are the same reference
alert (morePeople.indexOf ((name: 'Nicholas'))); //-1, because it is not the same reference
[Tips] returns all index values for items that meet the conditions.
function allIndexOf(array,value){
var result = [];
var pos = array.indexOf(value);
if(pos === -1){
return -1;
}
while(pos > -1){
result.push(pos);
pos = array.indexOf(value,pos+1);
}
return result;
}
var array = [1,2,3,3,2,1];
console.log(allIndexOf(array,1));//[0,5]
The above is the detailed content of this article, hoping to help you learn javascript programming.
Articles you may be interested in:
- JS array details
- Function for js to determine whether an array is used: isArray ()
- Js checks whether Object, Array, Function, and other reference type objects are equal
- Summary of some common methods for Array in js
- Js checks whether the parameter (String, Array, Object) is undefined or the value is null.
- How to Implement in_array using js
- How to transmit Array objects in JS to the background in JSON format
- Example of Array usage in JS
- Introduction to the sort () method of array in js
- ArrayBuffer in JavaScript