Javascript-an array of explanations

Source: Internet
Author: User
Tags javascript array

Preface

Plan to catch up with the changes, I would like to learn more about Python, but I have to go to JS Development, JS Basic 0 based on the case, recently also crazy to fill JS knowledge.
The spirit of good memory is not as bad as the faith, I decided to summarize the use of the array JS.

Create an array

There are several ways to declare an array in JS:

var arr = [];   // 简写模式varnewArray();  // new一个array对象varnewArray// new一个确定长度的array对象

To illustrate this:

Although the third method declares the length of the array, the array length is actually variable. That is, even if you specify a length of 5, the element can still be stored outside the specified length, and the length of the array will change accordingly.

In addition, there is a clear point to be made:

JS is a weakly typed language, which means that the element types in the array do not need to be the same.

Examples of inconsistent element types in arrays:

var arr = [1234‘wangzhengyi‘‘bululu‘];for (var0; i < arr.length; i ++) {    console.log(arr[i]);}
array element Access

The index value of the JavaScript array is also starting at 0, and we can access the array elements directly by using arrays name + subscript.

The sample code is as follows:

var arr = [123];console.log(arr[0]);console.log(arr[1]);

In addition, the traversal of the array is recommended for continuous for loop mode, not recommended for for-in, specific reason reference: Loop through array in JavaScript

The traversal array sample code is as follows:

var arr = [1234‘wangzhengyi‘‘bululu‘];for (var0, len = arr.length; i < len; i ++) {    console.log(arr[i]);}

Attention:

In the above code, a small optimization is to get the size of an array in advance, so that you do not need to query the array size each time you traverse. For a large array, it can improve some efficiency.

Adding an array element

There are three ways to add new elements to a previous array: Push, Unshift, splice. Let me introduce you to these three ways.

Push

The push method, which adds an element at the end of the array. The sample code is as follows:

var arr = [];arr.push(1);arr.push(2);arr.push(3);for (var0, len = arr.length; i < len; i ++) {    console.log(arr[i]);}

The result of the execution is:

123
Unshift

The Unshift method is to add elements to the head of the array. The sample code is as follows:

var arr = [];arr.unshift(1);arr.unshift(2);arr.unshift(3);for (var0, len = arr.length; i < len; i ++) {    console.log(arr[i]);}

The results of the implementation are as follows:

321
Splice

The splice method is to insert a new element at the specified position in the array, and the previous element is automatically sequentially moved back. Note that the function prototype for splice is:

array.splice(index, howMany, element...)

Howmany indicates the number of elements to delete, and if you just add elements, the howmany needs to be set to 0.

The sample code is as follows:

var arr = [1234];arr.splice(10789);for (var0, len = arr.length; i < len; i ++) {    console.log(arr[i]);}

The results of the implementation are as follows:

1789234
To Delete an array element

As with the addition of array elements, there are three ways to delete elements in an array: Pop, shift, and splice. Next, explain the usage of these three functions separately.

Pop

The Pop method is to move the last element in the divisor group. The combination of push and pop allows the array to be implemented similar to the stack (first-in, post-out) functionality. The sample code is as follows:

var arr = [];arr.push(1);arr.push(2);arr.push(3);while0) {    var ele = arr.pop();    console.log(ele);}
Shift

The shift method is to remove the first element, and the elements in the array are automatically moved forward. (This method certainly corresponds to the efficiency problem, the time complexity is O (n)).

var arr = [];arr.push(1);arr.push(2);arr.push(3);function traverseArray(arr) {    for (var0, len = arr.length; i < len; i ++) {        console.log(arr[i]);    }}while0) {    var ele = arr.shift();    traverseArray(arr);}

You can consider running the results yourself.

Splice

When adding array elements, we talked about splice, a function prototype that has a howmany parameter that represents how many elements have been removed since index.
The sample code is as follows:

var arr = [1234567];function traverseArray(arr) {    for (var0, len = arr.length; i < len; i ++) {        console.log(arr[i]);    }}arr.splice(13);traverseArray(arr);

The result of the execution is:

157
copying and interception of arrays

For example, the code is as follows:

var arr1 = [1234];var arr2 = arr1;

This time, arr2 just saves the address of the ARR1 array in the heap memory and does not re-request memory in the heap memory to engage an array out. So the modification of arr2 will affect the arr1 at the same time. So, what do we do if we need to copy an array? This leads to the slice and concat functions that need to be learned.

Slice

The slice here and the Python syntax are the same slice, all of which are the slices that return the array. The Slice function prototype is:

array.slice(begin, end)

Returns all elements from begin to end, noting that it contains begin, but does not contain end.
The default begin, starting from 0 by default. The default end, which defaults to the end of the array.

Therefore, the copy array can be implemented by the following code:

var arr1 = [1234];var arr2 = arr1.slice();arr2[210000function traverseArray(arr) {    for (var0, len = arr.length; i < len; i ++) {        console.log(arr[i]);    }}traverseArray(arr1);traverseArray(arr2);

The results of the implementation are as follows:

123412100004
concat

The Concat method creates a new array , then places the elements in the object that invokes it (the object that this is pointing to), and the elements in the parameters of the array type in all parameters, and the parameters of the non-array type themselves in the order of the new array, and returns the array.

The sample code is as follows:

var alpha = ["a""b""c"];var number = [123]// 新数组为["a", "b", "c", 1, 2, 3]var complex = alpha.concat(number);
implementation of sorting algorithm

My JS level is slag, so I write JavaScript sort algorithms in a way similar to Java and C.

And here I do not talk about the principle of arithmetic, just code implementation, there may be bugs, welcome to Blog Comments Guide.

Insert Sort

The algorithm description of Insert sort (insertion-sort) is a simple and intuitive sorting algorithm. It works by constructing an ordered sequence, for unsorted data, to scan from backward forward in the sorted sequence, to find the appropriate position and insert it. The insertion sort is implemented on an implementation, usually in the order of In-place (that is, the ordering of extra space using only O (1), so that in the backward-forward scanning process, the ordered elements need to be moved back and forth gradually, providing the insertion space for the newest elements.

The implementation code is as follows:

 function insertsort(arr) {    if(!arr)return;varlen = arr.length;if(len = =0|| Len = =1)return; for(vari =1, Len = arr.length; i < Len; i + +) {varStand = Arr[i]; for(varj = i-1; J >=0; J--) {if(Arr[j] > Stand) {arr[j +1] = Arr[j]; }Else{arr[j +1] = stand; Break; }        }    }returnarr;}

Time complexity: O (n^2)

Of course, the algorithm has room for optimization, for example, to change the location algorithm of search substitution to two-point lookup.

Bubble Sort

The classic sort algorithm that mentions bubble sort I just heartache. Undergraduate time must be paper bubble sorting algorithm improvement, the results after writing the paper can not complete the implementation of bubble sorting algorithm, good embarrassment.

    if(!arr)return;var Len= Arr.length;if(Len==0||Len==1)return; for(vari =0; I <Len; i + +) { for(varj =0; J <LenI1; J + +) {if(Arr[j] > arr[j +1]) {varTMP = Arr[j +1]; Arr[j +1] = Arr[j];            ARR[J] = tmp; }        }    }returnarr;}

Time complexity: O (n^2)

Quick Sort

Very classical sorting algorithm, the sorting process mainly I divided into three steps:

    1. Select an element from the series, called the "Datum" (pivot);
    2. Reorder the columns, where all elements are placed in front of the datum in a smaller position than the base value, and all elements are larger than the base value behind the datum (the same number can be on either side). After the partition exits, the datum is in the middle of the sequence. This is called partition (partition) operation;
    3. recursively (recursive) sorts sub-columns that are smaller than the base value elements and sub-columns that are larger than the base value elements.

The implementation code is as follows:

 function quickSort(arr, bt, ed) {    if(BT < ED) {varPivot = findpartition (arr, BT, ed); QuickSort (arr, BT, Pivot-1); QuickSort (arr, pivot +1, ed); }} function findpartition(arr, bt, ed) {    varStand = ARR[BT]; while(BT < ED) { while(BT < Ed && Arr[ed] >= stand)        {ED--; }if(BT < ED)        {ARR[BT + +] = arr[ed]; } while(BT < Ed && ARR[BT] <= stand)        {BT + +; }if(BT < ED)         {arr[ed--] = ARR[BT]; }} ARR[BT] = stand;returnBT;}

The complexity of Time is: O (NLOGN).

Merge Sort

is also a very classic sorting algorithm, I am learning JS by the opportunity to review the classic sorting algorithm. The idea of merging sort can refer to my blog: merge sort. I write only JS implementation here.

 function mergesort(arr, bt, ed) {    if(BT < ED) {varMID = BT +parseint((ED-BT)/2);        MergeSort (arr, BT, mid); MergeSort (arr, Mid +1, ed);            Mergearray (arr, BT, Mid, ed); }} function mergearray(arr, BT, Mid, ed) {    varMARR = [];vari = bt, j = mid +1; while(I <= Mid && J <= ed) {if(Arr[i] <= arr[j])        {Marr.push (arr[i++]); }Else{Marr.push (arr[j + +]); }    }if(I <= mid) {MARR = Marr.concat (Arr.slice (i, Mid +1)); }if(J <= ed) {MARR = Marr.concat (Arr.slice (J, ed +1)); } for(varh =0; H < marr.length;    H + +) {ARR[BT + h] = marr[h]; }}

Write merge sort when there is also a small episode: JS can not automatically take the whole, later with the parseint method, feeling Meng Meng big.

Javascript-an array of explanations

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.