Preface
Array is an important part of Javascript. It can be used to store strings, objects, functions, and Numbers. It is very powerful. Therefore, a deep understanding of Array is a compulsory front-end homework. It’s Friday, and the blogger’s heart is starting to surge again. Is there any weekend tomorrow? I can have fun again.
Create an array
There are two basic ways to create arrays, one is literal, and the other is created using constructors:
var arr = [1,2,3]; //Create array values in the form of literals and are separated by English commas
var arr = [1,2,3]; //Create array values in the form of literals and are separated by English commas var arr1 = new Array(1,2,3); //Constructor creates an array to create an Array object through the new operator//In addition, you can also omit the new operator, although it is not recommended to do this most of the time. var arr1 = Array(1,2,3); omit the new operator to create an Array object. This syntax is very similar to PHP, but its key cannot be specified in JavaScript.
Index of array: key-value pairs
Taking literals as an example, each array item has a corresponding key, which can also be called [subscript] and [index]. The default key in javascript starts from 0 and determines its key name according to the position of the array item. The value of the array item is queried through the key name. The general syntax is array[i]:
var sarr = ["hello","java","script"];//The corresponding key names are 0, 1, 2 console.log(sarr[0]); //hello
Print the arrays into the Firefox console, and you can clearly see their corresponding relationship in the console:
On the right side of the console, the logical relationship between keys and values is listed in a very intuitive way. 0 corresponds to hello, 1 corresponds to java, and 2 corresponds to script. More commonly, the javascript array count starts from 0 [0-1-2]==[1-2-3] The first one is hello, the second one is java, and the third one is script;
Each array has a length, no value is 0, and is obtained through the Array.length method. The length of the figure above is 3, which can be clearly seen on the right side of the console. In addition, a small trick is introduced. Most of the attribute lists listed in the Firefox console console console are directly accessible. You can access it through the [Array.length] number or access [Array['length']] through the form of a key;
The length property of an array is very distinctive-----it is not read-only. Therefore, by setting this property, you can remove items from the end of the array or add new items to the array, Chestnut:
var colors = ['red','blue','green'];//Create an array of 3 strings colors.length = 2;alert(colors[2]);//undefined does not exist
Shangli deleted the last item 'green' of the array and can also be added:
var colors = ['red','blue','green'];//Create an array of 3 strings colors[colors.length] = 'black'; //The initial length of colors is 3. This code is equivalent to colors[3] = 'black'; alert(colors[3]);//black
Tips 1:
So the question is, sometimes my friends suddenly forget a certain attribute name while knocking. What should I do?
Print it to the Firefox console, look at its properties, take the location object as an example console.log(location):
console.log(location);
After getting this, is it much easier for us to get a certain value? For example, if you get the current url address [location.href], get the domain name [location.hostname], etc., or if you want to get the method on Windows, this is the same, which is very convenient;
Array stack
What is an array stack? It means that arrays can be expressed as stacks (nonsense) So what is stack?
The understanding in the code is that the stack is a data structure that can restrict the insertion and deletion of items. The stack is a LIFO (Last-In-FIRST-Out, first-out), that is, the latest added item is removed first, and the earliest added item is at the bottom of the stack. See the picture:
Similar to building blocks, the building blocks below can always be obtained at the end. If placed in a new place, a [stack] is formed.
Take it out in the array stack and call it [pop] and put it in and call it [push]
There are two methods in the javascript array [pop()] [pushing is push()]
var sarr = ["hello","java","script"];sarr.push("black");//Pull in a blackconsole.log(sarr[3])//blackconsole.log(sarr.pop())//black //Pop black console.log(sarr[3]);//undefined black has been popped up so array item 3 does not existqueue
The access rule for stack data is LIFO (first in, and then out), while the access rule for queue data structure is FIF0 (first in, first out). Queues are often used to loop through arrays and continuously operate on arrays; queue methods use shift() to pop up advanced items from arrays, that is, items with subscripts of 0.
var sarr = ["hello","java","script"];console.log(sarr.shift()); //hello //shift is similar to pop method. Pop pops up from the end of the array and shift is from the beginning of the array console.log(sarr[0]); //java hello has been popped up
Use shift method to form a queue:
var sarr = ["hello","java","script"];var alf = sarr.shift();//Take out the first item sarr.push(alf);//Insert to console.log(sarr); //['java','script','hello']
Through the timer setInterval, we can continuously loop through each array item. The previous blog post has been explained. "Portal setTimeout and setInterval timer and asynchronous loop array.
setInterval(function(){console.log(sarr[0]);//Print the first item var alf = sarr.shift();//Take out the first item sarr.push(alf);//Insert to the end of the array},1000);Shangli will keep printing hello java script
We know that arrays can store values of any type. So we put the functions that need to be executed in a loop in the array and then use the queue method to continuously execute it, and then we can loop through the methods in the queue:
function hello(){console.log("hello");}function java(){console.log("java");}function script(){console.log("script");}var sarr = [hello,java,script];setInterval(function(){var alf = sarr.shift();//Take out the first item sarr.push(alf);alf();//Execute method},1000);It can also print hello java script loops, but it's more powerful
Summary of common methods of arrays
1. Sort
There are already two methods in the javascript array that can be directly used for reordering: reverse() and sort().
reverse() rearranges the array flashback:
var sarr = [1,2,3,4,5,6];console.log(sarr.reverse()); //6,5,4,3,2,1
There is also a more powerful method sort()
The default sort() reorders the array in ascending order. It should be noted that sort will call the toString() method of each item, so the actual size of sort is based on strings:
var sarr = [6,2,2,4,5,6];console.log(sarr.sort()); //2,2,4,5,6,6 Ascending order var sarr = [6,2,2,11,4,5,6]; console.log(sarr.sort()); //11,2,2,4,5,6,6
The actual comparison size of sort is a string. The comparison method of string is generally to compare the first character in the character, so '11'<2 'a'<'b'
sort can also pass a function as a parameter, which can redefine the sorting method of the array:
function compare(val1,val2){ //sort passes two parameters value 1 and value 2if(val1<val2){ //When value 1 is less than value 2 Return -1 means moving value 1 forward by one position return -1; }else if(val1>val2){return 1;}else{return 0;}}var sarr = [6,2,2,11,4,5,6];console.log(sarr.sort(compare)); //[ 2, 2, 4, 5, 6, 6, 11 ] We compare in the function and the final result is normalIf [val1<val2] returns 1 more than return -1, we can arrange it in a flash; we can also specify its sorting method ourselves;
2. Operand array
① Copy an array and save (clone) The concat() method can create a new array based on all items in the current array. When passing parameters, it will add the parameters to the end of the array together.
var sarr = ["hello","java","script"];var farr = sarr.concat("!");console.log(farr);//[ "hello", "java", "script", "!" ]② slice() It can create a new array based on one or more items in the current array. It can accept 1 or two parameters, that is, the beginning and end positions of the item to be copied. Only one parameter has the default end position at the end of the array, so it can also clone an array;
var sarr = ["hello","java","script"];var farr = sarr.slice(0);console.log(farr);//[ "hello", "java", "script" ]var farr = sarr.slice(0,1)console.log(farr);//Take out 0-1 and create a copy//[ "hello" ]
Summarize
Arrays are a very important part in JavaScript. Learning it well can simplify the code at work. Many times, you can try to put them in an array and perform a series of operations through the array method. The blog post is limited in length, but there is no limit to learning. I hope everyone can learn happily and master your front-end development faster!
The above is an analysis of common methods of arrays in Javascript introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!