Javascript data structure and algorithm-array

Source: Internet
Author: User
Tags array definition

Javascript data structure and algorithm-array
Array definition in Javascript

Arrays are only special objects in javascript. The property names of javascript objects must be strings.
Therefore, indexes used to indicate offsets are converted to strings internally.

Create an array

[] Operator

var Arr=[];
console.log(Arr.length);//0

var Arr=[1,2,3,4,5];
console.log(Arr.length);//5

Call the Array Constructor

var Arr=new Array(1,2,3,4,5);
console.log(Arr.length);//5

'Var Arr = new Array (10 );

Array methods 1. split () to generate an array

The string is divided into several parts by a separator, and each part is saved as an element in a new array.

var str='nice to meet you';var arr=str.split(" ");for(var i=0;i

2. indexOf () & lastIndexOf () Index

Used to check whether the passed parameter exists in the target array and return the index that appears for the first time. Otherwise,-1 is returned.LastIndexOf ()Similar to indexOf (), only the last index that appears is returned after retrieval.

var arr=['hi','hello','halo','hello'];console.log(arr.indexOf('hello');console.log(arr.lastIndexOf('hello'));

3. Convert the jion () & toString () array to a string

If jion () does not have a parameter, jion () and toString () convert the array to a string separated by commas. When jion () has a parameter, the array is converted to a string with this parameter as the separator.

var arr=['hi','hello','halo','hello'];console.log(arr.join());console.log(arr.toString());console.log(arr.join('||'));

4. splice () & concat () creates a new array from an existing number of groups

Concat () merges multiple arrays, and A. concat (B, C) generates A new array in sequence from A-> C;
Splice (a, B, c) has three parameters, and the function is also determined by these three parameters. If there are only two parameters, it means that B elements are intercepted from index, if there are three parameters, it means that the index a is used to intercept B elements and insert c elements into the index. The c element can be multiple elements.
Splice generates a new array and changes the old array.

var arr1=['hi1','hello1','halo1','hello1'];var arr2=['hi2','hello2','halo2','hello2'];console.log(arr1.join());console.log(arr2.join());var arr3=arr1.concat(arr2);var arr4=arr1.splice(2,1);console.log(arr1.join());console.log(arr2.join());console.log(arr3.join());console.log(arr4.join());

5. push () & unshift () add elements to the array

Push () adds the element to the end of the array.
Unshift () adds the element to the beginning of the array.

var arr=['b','c','d'];console.log(arr.join());arr.push('e');console.log(arr.join());arr.unshift('a');console.log(arr.join());

6. pop () & shift () deletes elements from the array.

Pop () deletes the elements at the end of the array.
Shift () deletes elements starting with an array.

var arr=['a','b','c','d','e'];console.log(arr.join());arr.pop();console.log(arr.join());arr.shift();console.log(arr.join());

7. reverse () & sort () is sorted by ARRAY

Sort details
Elements in the reverse () array are arranged in reverse order.

var arr=['a','b','c','d','e'];console.log(arr.join());arr.reverse();console.log(arr.join());

8. The iterator forEach () that does not generate a new array accepts a function as a parameter and executes this function for each element of the array. This function does not return values.
Var arr = [1, 2, 3, 4, 5, 6]; function square (num) {console. log (the square of num + 'is' + num * num)} arr. forEach (square );

Every () accepts a function whose return value is of the bool type and executes this function on each element of the array. If true is returned for all elements, every () returns true.

Some () accepts a function whose return value is of the bool type and executes this function on each element of the array. If one element executes this function and returns true, some () returns true. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + cmVkdWNlKCm908rc0ru49rqvyv3X986qss7K/aOsttTK/dfpw7/large + fill = "brush: java;"> var arr=[1,2,3,4,5,6,7,8,9]; function add(e,f) { return e+f; } var arrStr=arr.reduce(add); console.log(arr.join()); console.log(arrStr);


-ReduceRight () accepts a function as a parameter. If you execute this function on each element of the array in reverse order, a value is returned. reduce accumulates the result and returns the accumulated value.

var arr=['1','2','3','4','5','6','7','8','9'];    function add(e,f) {        return e+f;    }    var arrStr1=arr.reduce(add);    var arrStr2=arr.reduceRight(add);    console.log(arr.join());    console.log(arrStr1);    console.log(arrStr2);

8. iterator for generating new Arrays

Similar to forEach (), map accepts a function as a parameter and executes the function on each element of the array, but the function returns a value.

var arr1=[1,2,3,4,5,6];    function square(num){        return num*num;    }    var arr2=arr1.map(square);    console.log(arr1);    console.log(arr2);

Similar to every (), filter accepts a function whose return value is of the bool type and executes this function on each element of the array. filter returns a new array, the new array includes all elements that execute the function and return true.

var arr1=[1,2,3,4,5,6];    function iseven(num){        return num%2==0;    }    var arr2=arr1.filter(iseven);    console.log(arr1);    console.log(arr2);

9. Copy an array
In simple copy, an array is directly assigned to another array, which only adds a reference to the original array.
var arr1=[1,2,3,4,5,6];    var arr2=arr1;    console.log(arr1);    console.log(arr2);    arr1[0]=9999;    console.log(arr1);    console.log(arr2);

Deep Replication
We can customize a copy () method for deep replication.
var arr1=[1,2,3,4,5,6];    var arr2;    copy(arr1,arr2);    console.log(arr1.join());    console.log(arr2.join());    arr1[0]=9999;    console.log(arr1.join());    console.log(arr2.join());    function copy (arr1,arr2) {        for (var i = 0; i 

10. Create a two-dimensional array
Array.matrix=function(row,col,int){        var arr=[];        for (var i = 0; i < row; i++) {            var cols=[];            for (var j = 0; j < col; j++) {                cols[j]=int;            };            arr[i]=cols;        };        return arr;    }    var nums=Array.matrix(5,5,'Liz');    console.log(nums.join());

11. Uneven Creation

In fact, you only need to know the number of rows.
Create an array with N rows and 1 columns first. If necessary, add

12. process two-dimensional arrays

It can be divided into two types: Row-based traversal and column-based traversal.

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.