Basic usage of JavaScript arrays

Source: Internet
Author: User

In fact, arrays, strings and so on are just beginning to learn JS when the beginning of contact, then just a simple API learning, and even the API has not been able to remember. After several such pains, I finally decided to write a blog post to strengthen the memory, of course, will add some of their own understanding.

1 Sparse arrays

As for how to create an array, there are several ways to create an array, which I am not going to describe here. Let's start by talking about sparse arrays.

A sparse array is an array that contains a discontinuous index starting at 0, and usually the length of the sparse array is greater than the number of elements in the array. As an example,

// how to produce a sparse array        var arr04=[];        arr04[9]=1;        Alert (arr04.length)   //10        alert (arr04[1]);      Undefined        alert (in arr04) ;    False

In the example we define an empty array and then specify Arr04[9]=1, where the length property value of the array is 10, but the number of elements in the array is only 1, because when we use in to determine whether an element at index 1 returns false. No element returned by default is undefined. Of course, if this is the case, it will return true.

var arr03=[0,1,2,3,null, undefined];        Alert ( in arr03); // determines whether index 4 has a value, even if the value that is stored in the index is null and undefined also returns true         in arr03);

Returns true even if the value that is stored in the index is null and undefined.

Okay, so much for sparse arrays, what's the use of sparse arrays, and where to use them, little brother Caishuxueqian, currently unknown.

2 Deleting an array element

There are 4 ways to delete an array element: The delete operator, pop (), Shift (), and Splice (). Delete Does not change the length of the element group, but instead transforms the original array into a sparse array. Both pop () and shift () change the length of the array directly. Splice () to speak back.

The Pop () method is to delete the element pointed to by the highest index of the array, and shift () is to delete the element that the lowest index points to (Arr[0]. See Routines:

        var arr05=[0,1,2,3];        Console.log (arr05.length+ "---" +arr05)//4---0,1,2,3        Delete arr05[1];        Console.log (arr05.length+ "---" +arr05);//---0,,2,3        alert (in arr05)  //false
var arr05=[0,1,2,3];        Arr05.pop ()              console.log (arr05.length+ "---" +arr05);  3---0,1,2   delete the last element of the array, the length will be reduced by one
       var arr05=[0,1,2,3];        Arr05.shift ()              console.log (arr05.length+ "---" +arr05);  // 3---   the first element of the array is deleted, and the length is reduced by one

3 Array Traversal

I believe the first thing to think about is to use a for loop, which is really a good way to do this, not here for example.

If you want to use this method to skip elements that are null, undefined, and nonexistent in the process of iterating over an array, we can do this:

var arr06=[1,2,3,null, 4,undefined,5,,];          for (var i=0;i<arr06.length;i++) {            if(!arr06[i])continue;            Console.log (i+ "----" +arr06[i]);        }

And, of course, the traversal of elements that exist.

var arr06=[1,2,3,null, 4,undefined,5,,];          for (var i=0;i<arr06.length;i++) {            if in arr06)) Continue ;            Console.log (i+ "----" +arr06[i]);        }

If you want to skip elements that are undefined and do not exist, you can do this:

var arr06=[1,2,3,null,4,undefined,5,,];
 for (var i=0;i<arr06.length;i++) {            if(arr06[i]===undefined)continue;            Console.log (i+ "----" +arr06[i]);        }

Then it is traversing with for. Cases:

var arr06=[1,2,3];          for (var in arr06) {            Console.log (index+ "----" +Arr06[index]);        }

But there's a problem with for-in, and when we customize some of the prototype properties, these properties are also traversed. Cases:

var arr06=[1,2,3];        Array.prototype.test=5;          for (var in arr06) {            Console.log (index+ "----" +Arr06[index]);        }

Of course, some of the prototype properties built into the array, such as Join,map, are not traversed. It is generally not recommended to use this method, because you may not know whether someone in your code has added a method or attribute to the prototype, resulting in a lot of unexpected results for the last for-in-time duration. Of course, you can use the following methods to eliminate these unexpected results.

 for (var in arr06) {            if(!arr06.hasownproperty (index))continue;            Console.log (Index+ "----" +Arr06[index]);        }

Another way is to use ES5 new Method-foreach () As for the introduction of this method you can see this blog post

4 Basic methods of arrays

Join (): Converts all elements in the array into strings, and finally returns the string. It takes a parameter that represents the delimiter between each element, and of course the argument is optional. Array.join is the reverse operation of String.Split. This set of operations is very useful, but also hope that you can understand the use. See Routines:

var arr06=[1,2,3];         var str= "the";        Console.log (Arr06.join ("-"));  It  has been converted to string        Console.log (Str.split ("-"));   ["1", "2", "3"]  has been converted to an array

Reverse (): The Order of the elements of the array is reversed, for example, when the operation is [[+]], it becomes [3,2,1]. Here I no longer an example, want to steal a little lazy, write too tired, do not want to be too wordy.

Sort (): This function is a function of sorting an array of elements, and if you do not pass the arguments, the elements of the arrays are sorted by string, and here we should all know that the size of the string comparison is actually compared to the size of their ASCII value, the ASCII code of "A" in ASCII is 97 and The ASCII code for "a" is 65,97 greater than 65, so the result of a string comparison should be "a" greater than "a". In the sort function, you compare the size of the ASCII of the corresponding position character in the two elements one after the other. For example: "ABCD" and "ABCE", the first three characters "ABC" are the same, in fact, the last comparison is "D" and "E" ASCII code values.

var arr07=["J", "D", "L"]console.log (Arr07.sort ());//["D", "J", "L"]

Of course, if the array element is a number, then the sort function converts the number to a string for comparison, without actually comparing the values, see the routines:

var arr07=[3,15,4]console.log (Arr07.sort ());//[15, 3, 4]  the ASCII value of "1" should be less than "3"

If you want to do a real numeric sort, this gives the sort a parameter, which is a comparison function. Cases:

var arr07=[3,15,4]        console.log (Arr07.sort (A,b) {            return A-b;        });   [3, 4, the]

The comparison rule is that assuming that the first argument should precede, the comparison function should return a value less than 0, return a value greater than 0, and return 0 if the two number is the same size as the previous one. If it is from the big to the small row, we only need to change to return b-a;

Concat (): array concatenation. Directly on the routine self-experience

var arr08=[0,1,2];         var arr09=[3,4];         var arr10=[5,6];        Console.log (Arr08.concat (arr09));//[0, 1, 2, 3, 4]        Console.log (Arr08.concat (ARR09,ARR10));//[0, 1, 2, 3, 4, 5, 6]< C10/>console.log (Arr08.concat (arr09,arr10,[7,8,[9,10]));//[0, 1, 2, 3, 4, 5, 6, 7, 8, [9,10]]

Slice (): Returns a fragment or sub-array of the specified array. The routines are as follows

  var  arr11=[0,1,2,3,4,5,6]; // Console.log (Arr11.slice (0,3)); // [0, 1, 2]  console.log (Arr11.slice (3,1)); // ["This gets an empty array  console.log (Arr11.slice (3)); // [3, 4, 5, 6] does not specify a second parameter, which means intercepting all array elements from the third element until the last  console.log (Arr11.slice (0,-1)); // [0, 1, 2, 3, 4, 5] Negative number represents the penultimate  Console.log (Arr11.slice ( -5,-3)); // [2, 3] intercepts the element from the bottom fifth to the 3rd of the bottom  Console.log (Arr11.slice ( -3,-5)); // [] empty array  

Splice (): This method is a common method for inserting and deleting elements in an array. Its first parameter specifies the starting position of the insertion or deletion, the second parameter represents the number of deletions, and if not specified, means that all elements from the specified position to the end of the array are deleted, and finally the deleted element array is returned. Returns an empty array if the element is not deleted.

var arr12=[1,2,3,4,5,6,7,8];        Console.log (Arr12.splice (4) + "-Original array:" +arr12);        Console.log (arr12.splice) + "-Original array:" +arr12);        Console.log (arr12.splice) + "-Original array:" +arr12);        Console.log (Arr12.splice (1,0) + "-Original array:" +arr12);

Splice () The first two parameters specify the starting position of the deletion and the number of deleted elements, after which any parameter represents the element to be inserted. Cases:

Arr12.splice (1,0, "DJL");//[1, "Djl", 2, 3, 4, 5, 6, 7, 8]        Arr12.splice (the "DJL");//[1, "Djl", 3, 4, 5, 6, 7 , 8]

Push () and pop ():

Push () appends an element to the end of the array, pop (): Deletes the last element of the array. Will change the length of the original array directly. No longer an example, tired.

Shift () and unshift ()

Shift (): Deletes the first element of the array; Unshift (): Adds an element to the front of the array. It will also change the length of the original array directly.

ToString (): Converts each array element to a string and separates each element with a comma, as it does with a join method that does not pass in the parameter.

At present so many, already enough, can patiently see here, must treat oneself well!

Basic usage of JavaScript arrays

Related Article

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.