Front-end development: arrays in JavaScript, common methods for parsing

Source: Internet
Author: User
Tags setinterval javascript array

Front-end development: arrays in JavaScript, common methods for parsing

Objective

Array is an important part of JavaScript that can be used to store strings, objects, functions, and number, which is very powerful. So an in-depth understanding of array is a prerequisite for the front end. Friday, the blogger's heart began surging, tomorrow weekend there are wood, but also happy to play.

Create an array

There are two basic ways to create an array, one literal, and the other using constructors to create:

var //  varnew Array (+/-); // constructor creates an array with the new operator creates an array object

Alternatively, you can omit the new operator

Array (+/-); omit the new operator to create an array object this syntax is very similar to PHP, except that its keys are not specified in JavaScript .

 Index of the array: key-value pairs

In the case of literals, each array item has a corresponding key, which can also be called subscript, index, and the default key in JavaScript starts from 0. The key name is determined by the position of the array item, the value of the array item is queried by the key name, and the general syntax is array[i]:

var sarr = ["Hello", "java", "script"];      //      Console.log (sarr[0]);  // Hello

By printing the array to the Firefox console, you can clearly see their corresponding relationships in the console:

The right side of the console is very intuitive to list the key and value of the logical relationship 0 corresponds to Hello, 1 corresponds to Java, 2 corresponding script, more commonly speaking JavaScript array count is starting from 0 "0-1-2" = = "" "The first one is hello second is Java The third one is script;

Each array has a length, no value of 0, obtained by the Array.Length method, the length is 3, on the right side of the console can also be clearly seen, in addition to a small tip, the Firefox console console list of the list of properties are most directly accessible you can go through the " Array.Length "can also access" array[' Length "in the form of a key;

The length property of an array is very characteristic------it is not read-only. So, by setting this property, you can either remove the item from the end of the array or add a new item to the array, chestnut:

var colors = [' Red ', ' blue ', ' green ']; // Create an array containing 3 strings colors.length = 2; alert (colors[2]); //

Shangli Delete the last item of the array ' green ' can also be added:

var colors = [' Red ', ' blue ', ' green ']; // Create an array containing 3 strings colors[colors.length] = ' black ';//colors's initial length is 3  This code is equivalent to colors[3] = ' black ' ; Alert (colors[3]); // Black

Tip # 1:

Then the question comes, and the little friends sometimes knock and suddenly forget a property name.

Print it to the Firefox console, and look at its properties. Console.log (location) is an example of a location object:

Console.log (location);

Get this, we want to get a value is not much easier. For example, get the current URL address "location.href" Get the domain name "location.hostname" and so on, or you want to get the method on the window, this kind of similar, very convenient;

Array stacks

What is an array stack?  It means that the array can behave like a stack (fart) What is a stack? This is the stack-Baidu encyclopedia

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 LIFO), that is, the most recently added item is first removed, and the first added item is at the bottom of the stack, looking at the graph:

Similar to the building blocks, the following bricks are always the last to get, put in a new place, formed a "stack"

Take it out of the stack and call it "eject" and put it in the "push-in".

There are two methods in the JavaScript array "pop is pop ()" "Push in Is push ()"

var sarr = ["Hello", "java", "script"];sarr.push ("Black"); // push into a black Console.log (sarr[3]) // Black Console.log (Sarr.pop ()) //  console.log (sarr[3]); // undefined  Black has been ejected, so array entry 3 does not exist

Queue

The access rules for the stack data are LIFO (advanced-out), while the access rules for the queue structure are FIF0 (FIFO). Queues are often used to iterate over arrays of operations, and queue methods use Shift () to eject advanced items, which are subscript 0, from an array.

var sarr = ["Hello", "java", "script"//Hello    //shift similar to pop method, pop pops from the end  of the array While shift is from the beginning of the array console.log (sarr[//java   Hello has been popped

Use the Shift method to form a queue:

var sarr = ["Hello", "java", "script"]; var alf = Sarr.shift (); // Remove the first Sarr.push (ALF); // insert to end of array // [' Java ', ' script ', ' hello ']

With the timer setinterval we can constantly cycle through each array of items SetInterval previous posts have been explained "portal settimeout and SetInterval timers and asynchronous loop arrays

SetInterval (function() {    console.log (sarr[0]);   Print the first item    var alf = Sarr.shift ();   Remove the first    Sarr.push (ALF);   Insert to end of array },1000);

Shangli will continue to print Hello Java script

We know that arrays can store values of any type so we can loop through the methods in the queue by putting the functions that need to be executed in the loop in the array and then using the queue method to execute continuously:

 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 (); //  Remove the first item      Sarr.push (ALF); Alf ();  //  Execute method },1000); 

It can also be recycled to print Hello Java script just more powerful

Summary of common methods for arrays

1. Sorting

There are already two methods in the JavaScript array that can be used for reordering directly: reverse () and sort ().

Reverse () rearrange the array flashback:

var sarr = [1,2,3,4,5,6//6,5,4,3,2,1

There's a more powerful way to sort ()

The default sort () is to rearrange the array in ascending order, noting that sort calls the ToString () method of each item, so the sort actual comparison size is based on a string :

var sarr = [6,2,2,4,5,6//2,2,4,5,6,6  Ascending order
var Sarr = [6,2,2,11,4,5,6];

Shangli, because the sort actual comparison size is based on a string and the string comparison method is usually taken by the first character in the characters to compare, so ' one ' <2 ' a ' < ' B '

The sort can also pass a function as a parameter, which can re-specify how the array is sorted:

functionCompare (Val1,val2) {//sort passes two parameter values of 1 and value 2    if(VAL1&LT;VAL2) {//a value of 1 is less than 2 returns-1 means that the value 1 moves forward one position        return-1; }Else if(val1>val2) {        return1; }Else{        return0; }}varSarr = [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 normal.

Shangli if "Val1<val2" returns 1 greater than return-1, it can be staggered, we can also specify its own way of sorting;

2. Manipulating arrays

① copy a copy of an array save (clone) The Concat () method can create a new array based on all the items in the current array, passing the arguments, and adding the parameters to the end of the array

var sarr = ["Hello", "java", "script"]; var farr = Sarr.concat ("!" ); Console.log (Farr); // ["Hello", "java", "Script", "!"]

②slice () It is able to create a new array based on one or more items in the current array, it can accept 1 or two parameters, that is, to copy the start and end of the item, only one of the default end position of the parameter is at the end of the array, so it can also clone a set;

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); // Remove 0-1 Create copy//["Hello"]

There are a lot of ways and so on and so on ... Refer to the W3shool JavaScript manual

Summarize

The array in JavaScript is a very important part, learn it can simplify the work of the code, many times your long list of operations can try to put them in the array by array method to carry out a series of operations; the length of the blog is limited, the study has no boundaries, I hope you can enjoy learning, Master your front-end development faster!

How long is---------------------------------------life? Hundred years, but how wide can it be? 200 pounds? ---------------------------------------

My number: QQ:

Welcome all kinds of technical discussion, if you have to build station needs, welcome to contact;

(reproduced please specify the source)

Front-end development: arrays in JavaScript, common methods for parsing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.