JavaScript array common methods _javascript tips

Source: Internet
Author: User
Tags array length prev javascript array

To determine whether an object is an array: instanceof, Array.isarray ()

You can use the instanceof operator for a Web page or a global scope.

if (value instanceof Array) {//To determine if value is an array

}
Instanceof operator It assumes that there is only one global execution environment, and if the Web page contains more than one frame, the ECMAScript5 new Array.isarray () method is used.

if (Array.isarray (value)) {//To determine if value is an array

}
The Array.isarray () method supports browsers such as ie9+, Firefor 4+, safari5+, Opera 10.5+, and Chrome.

If you want to check the array in a browser that does not implement this method, use:

if (Object.prototype.toString.call (value) = = "[Object Array]") {
}

Converts an array to a string: toLocaleString (), toString (), valueof (), join ()

Copy Code code as follows:

var test=[' A ', ' B ', ' C '];
Alert (test.tostring ());//a,b,c
Alert (test.tolocalestring ());//a,b,c
Alert (test.valueof ());//a,b,c
alert (test);//a,b,c default Call ToString () method
Alert (Test.join (', '));//a,b,c
Alert (test.join (' | ')); /a|b|c

Add and move an array element method: Push (), pop (), Unshift (), Shift ()

The push () method can accept any number of arguments, adding them to the end of the array one by one, and returning the modified array length of the array.

The Pop () method removes the last item from the end of the array, and then returns the removed item.

The Unshift () method adds any number of arguments to the front of the array and returns the new array length.

The shift () method moves the first item in the divisor group and returns the removed item.

Copy Code code as follows:

var test=[];
var count = Test.push (' A ', ' B ');//Add one by one from the end of the array
Count =test.push (' C ');
alert (count);//3
alert (test);//
var item = Test.pop ();
alert (item);//c
alert (test.length);//2

Sorting methods: Reverse () and sort ()

The reverse () method reverses the array entry, manipulating the array itself.

The sort () method arranges the array items in ascending order by default, manipulating the array itself.

Copy Code code as follows:

var test=[1,2,3,4,5];
Test.reverse ();
alert (test);//5,4,3,2,1
var test2=[0,1,5,10,15];
Test2.sort ();
alert (test2); the//0,1,10,15,5 sort () method invokes the ToString () method of each array item, comparing the string to determine the sort. So here sort of is the string sort

The sort () method can also pass in a comparison function.

The comparison function returns a negative number before the first argument should be in the second, and returns 0 if the two arguments are equal, and the first parameter should return a positive number after the second.

Copy Code code as follows:

function Compare (value1,value2) {
if (value1<value2) {
return-1;
}else if (value1>value2) {
return 1;
}else{
return 0;
}
}
var test=[0,1,5,10,15];
Test.sort (Compare);
alert (test);//0,1,5,10,15

How to: Concat (), slice (), splice ()

The Concat () method is used to connect two or more arrays. This method does not change an existing array, but merely returns a copy of the connected array. Returns a new array.

Copy Code code as follows:

var a = [1,2,3];
Alert (A.concat (4,5));//1,2,3,4,5
var arr = new Array (3)
Arr[0] = "George"
ARR[1] = "John"
ARR[2] = "Thomas"
var arr2 = new Array (3)
Arr2[0] = "James"
ARR2[1] = "Adrew"
ARR2[2] = "Martin"
Alert (Arr.concat (ARR2));
George,john,thomas,james,adrew,martin
var arr = new Array (3)
Arr[0] = "George"
ARR[1] = "John"
ARR[2] = "Thomas"
var arr2 = new Array (3)
Arr2[0] = "James"
ARR2[1] = "Adrew"
ARR2[2] = "Martin"
var arr3 = new Array (2)
Arr3[0] = "William"
ARR3[1] = "Franklin"
Alert (Arr.concat (ARR2,ARR3))
George,john,thomas,james,adrew,martin,william,franklin

The slice () method returns the selected element from an existing array. Returns a new array containing the elements in the arrayobject from start to end (excluding the element).

Copy Code code as follows:

var test =[' A ', ' B ', ' C ', ' d ', ' e '];
var arr1=test.slice (1);
var arr2=test.slice (1,4);
alert (arr1);//b,c,d,e
alert (ARR2);//b,c,d

The splice () method adds/deletes items to/from the array, and then returns the items that were deleted. Manipulate the array itself.

First argument: Start position, second argument: number of intercepts, third argument: Append new element.

Copy Code code as follows:

Delete
var test=[' A ', ' B ', ' C '];
var removed=test.splice (0,1)//delete first item
alert (test);//b,c
alert (removed);//a returns the item that was deleted
Insert
var test2=[' A ', ' B ', ' C '];
var removed2=test2.splice (1,0, ' d ', ' e ')//is inserted starting at position 1 D,e
alert (test2);//a,d,e,b,c
Alert (REMOVED2)//empty array
Replace
var test3=[' A ', ' B ', ' C '];
var removed3=test3.splice (1,1, ' d ', ' e ')//is inserted starting at position 1 D,e
alert (TEST3);//a,d,e,c
Alert (REMOVED3)//b

Location method: IndexOf (), LastIndexOf ()

ECMASCRIPT5 provides methods to support browsers: ie9+, Firefox, Safari 3+, Opera 9.5+, Chrome

The IndexOf () method returns the location of the first occurrence of a specified string value in a string.

The LastIndexOf () method returns the last occurrence of a specified string value, which is searched forward at the specified position in a string.

A parameter: Represents the value to find, returns the index position (starting from 0), two arguments: The first parameter represents the starting position, and the second parameter represents the value to find.

Copy Code code as follows:

var numbers=[1,2,3,4,5,4,3,2,1];
Alert (Numbers.indexof (4));//3
Alert (Numbers.lastindexof (4));//5

Alert (numbers. IndexOf (4,4));//5
Alert (Numbers.lastindexof (4,4));//3

Iteration method: Every (), filter (), ForEach (), map (), some ()

ECMASCRIPT5 provides methods to support browsers: ie9+, Firefox, Safari 3+, Opera 9.5+, Chrome

Every (): Runs the given function for each item in the array, and returns True if the function returns true for each item.

Filter (): Each item in an array runs the given function, returning an array of items that the function returns True.

ForEach (): Runs the given function for each item in the array, and this method has no return value.

Map (): Each item in an array runs the given function, returning an array of the results of each function call.

Some (): Runs the given function for each item in the array, and returns True if the function returns true for either item.

None of the above functions will modify the values contained in the array.

Copy Code code as follows:

var numbers=[1,2,3,4,5,4,3,2,1];
Every ()
var everyresult=numbers.every (function (Item,index,array) {
return (ITEM>2);
})
alert (everyresult);//false
Some ()
var someresult=numbers.some (function (Item,index,array) {
return (ITEM>2);
})
alert (someresult);//true
Filter ()
var filterresult=numbers.filter (function (Item,index,array) {
return (ITEM>2);
})
alert (Filterresult);//[3,4,5,4,3]

Map ()
var mapresult=numbers.map (function (Item,index,array) {
return (ITEM*2);
})
alert (Mapresult);//[2,4,6,8,10,8,6,4,2]

ForEach ()
Numbers.foreach (function (Item,index,array) {
No return value to perform operation
})

Merge method: Reduce (), reduceright ()

ECMASCRIPT5 provides methods to support browsers: ie9+, Firefox 3+, Safari 4+, Opera 10.5+, Chrome

Two methods will iterate over the group's entries, and then build a final return value. The reduce () method begins with the first item of the array, and the Reduceright () method starts at the end of the array.

Copy Code code as follows:

var values=[1,2,3,4,5];
var sum=valuse.reduce (function (Prev,cur,index,array) {
Prev+cur;
});
alert (sum);//15

The above is the entire content of this article, I hope you can enjoy.

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.