Common methods for JavaScript array arrays _javascript tips

Source: Internet
Author: User
Tags javascript array

(1) Basic Array method

1.join ()

The Array.join () method converts all elements in an array to strings and joins together to return the last generated string. You can specify delimited symbols yourself, and if unspecified, use commas by default

var arr = [1,2,3];
Console.log (Arr.join ());//"1,2,3"
Console.log (Arr.join ("-"))//"1-2-3"

var a = new Array (10);//empty array of length 10 Composes the bottom string
console.log (A.join ("-)");/"---------"

2.reverse ()
the Array.reverse () method reverses the order of the elements in the array, returning an array in reverse sequence (the returned array is itself, the original array has changed)

var arr = [1,2,3];
Arr.reverse ();
Console.log (Arr.join ());//"3,2,1"

So, if you want to reverse a string, you can do so

var str = "ABCDEFG";

Console.log (Str.split (""). Reverse (). Join (""));//"GFEDCBA" returns the new value
console.log (str); "ABCDEFG" Of course, the original is not change.

3.sort ()
the Array.Sort () method sorts the elements in the array and returns the sorted array.

When not with parameters, the default is sorted by order, that is, from small to large. Of course, you can also directly give sort plus a comparison function comparison

var arr = [1,4,7];
Arr.sort ();
Console.log (arr); [1,4,7]

arr.sort (function (a,b) {return
 a-b;//From Small to large
});
Console.log (arr); [1,4,7]

arr.sort (function (a,b) {return
 b-a;//from large to small
});
Console.log (arr); [7,4,1]


var num = new Array (' One ', ' three ', ' Six ', ' Five ');
Num.sort (); case-sensitive sort
console.log (num);//["Five", "Six", "One", "three"]
num.sort (function (s,t) {
 var a = S.tolowercase ();
 var B = t.tolowercase ();
 if (a<b) return-1;
 if (a>b) return 1;
 return 0;
});
Console.log (num); ["Five", "One", "Six", "three"]

4.concat ()
the Array.concat () method creates and returns a new array whose elements include the elements of the original array that called CONCAT () and each parameter of concat ().

If any of these parameters are arrays, then the elements of the array are concatenated, not the array itself.

Note, however, that concat () does not recursively flatten arrays of arrays. Concat () also does not modify the array of calls.

var arr = [1,2,3];
Console.log (Arr.concat (4,5)); [1, 2, 3, 4, 5]
console.log (arr);       [1, 2, 3]
Console.log (Arr.concat ([4,5]));//[1, 2, 3, 4, 5]
Console.log (Arr.concat ([4,5],[6,7]));//[1, 2, 3, 4, 5,6,7]
console.log (Arr.concat ([4,[5,[6,7]]));//[1, 2, 3, 4, [5, [6, 7]]]
console.log (Arr.concat (4,[5,[6,7 ]])); [1, 2, 3, 4, 5,[6,7]]

5.slice ()
the Array.slice () method returns a fragment or a child array of the specified array. Its two parameters specify where fragments start and end, respectively (A,B). Returns an array element that does not include B from start A to B.
If there is only one argument (a). Represents the element from a to the end of an array.
If there is a negative number (-a) in the parameter. Represents the position of a relative to the last element in the array. For example (-3) represents the penultimate element to the end. A negative number is first converted, and then followed by the scope rules to find out
He also returns the new array and does not modify the original array

var arr = [1,2,3,4,5];
Console.log (Arr.slice (0,3)); [1, 2, 3]
console.log (arr);//[1, 2, 3, 4, 5]
Console.log (Arr.slice (3));//[4, 5]
Console.log ( Arr.slice ( -3));//[3, 4, 5]
Console.log (Arr.slice ( -3,-1));//[3, 4]
Console.log (Arr.slice (2,-1));//[3, 4]

6. Splice ()
the Array.splice () method is a common way to insert or delete elements in an array. It modifies the value of the original array and returns a new array sequence

The first parameter of splice () specifies the starting position of the insertion or deletion, and the second parameter specifies the number of elements that should be removed from the array. The second argument omitted deletes to the end by default.

var arr = [1,2,3,4,5,6,7,8];
Console.log (Arr.splice (4)); [5, 6, 7, 8]
console.log (arr);//[1, 2, 3, 4]
Console.log (Arr.splice (1,2));//[2, 3]
console.log (arr); 1, 4]

The first two parameters of splice () specify the array elements that need to be deleted. Any number of parameters immediately following specifies the element that needs to be inserted into the array and inserts from the position represented by the first argument.

Unlike the top concat (), splice () inserts the array directly into it, such as the following [1,2]

var arr = [1,2,3,4,5];
Console.log (Arr.splice (2,0, ' A ', ' B ')); []
Console.log (arr);//[1, 2, "a", "B", 3, 4, 5]
Console.log (Arr.splice (2,1,[1,2],3));//["a"]
Console.log (arr); [1, 2, [1, 2], 3, "B", 3, 4, 5]

7.push () Pop () unshift () Shift ()
think of these methods as stack operation on the line: the first two normal stack operations, the latter two are reverse stack operations
Push () and unshift () add elements from the back and front to the array, and return the length of the new array
Pop () and shift () delete the last and most previous elements in the array and return the deleted elements

var arr = [];

Console.log (Arr.push (1,2,3)),//3
console.log (arr);//[1, 2, 3]

Console.log (Arr.pop ());//3
Console.log (arr);//[1,2]

Console.log (Arr.push ([4,5]));//3
Console.log (arr);//[1, 2, [4, 5]]
var arr = [];

Console.log (Arr.unshift (1,2,3));//3
Console.log (arr);//[1, 2, 3]

Console.log (Arr.shift ());//1
Console.log (arr)//[2, 3]

Console.log (Arr.unshift ([4,5]))//3
Console.log (arr);//[[4, 5], 2, 3]

(2) Array method in ECMAScript5

Most of these array methods have uniform general rules. Neither of them modifies the original array.
The first parameter of most methods receives a function, and each element of the array (or some elements) calls the function once.

If it is a sparse array, the passed function is not invoked on elements that do not exist;
In most cases, the called function typically uses three parameters: the array element, the index of the element, and the array itself. Usually the latter two parameters do not need to be filled in.
In addition to the first argument (function) Here, there is a second argument (optional), and if the second argument exists, the called function is considered the method of the second argument.
That is, the second parameter passed in when the function is invoked is used as the value of its this keyword.

1.forEach ()

This method iterates through the array, calling the specified function for each array.

var data = [1,2,3,4,5];
var sum = 0;
Data.foreach (function (value) {///only uses the first parameter (functions), and the function that is called uses only the first parameter array element
 sum = value;
});

Console.log (sum);//15
console.log (data);//[1, 2, 3, 4, 5]
var data = [1,2,3,4,5];
var sum = 0;
Data.foreach (function (value,item,data) {//called functions have three parameters
  data[item] = value*value;//Take Squared
});

Console.log (data);//[1, 4, 9, 16, 25]

2.map ()
This method passes each element in the called array to the specified function and returns an array that contains the return value of the function.

var data = [1,2,3,4,5];
var data1 = Data.map (function (value) {return
 + + value;
});

Console.log (data); [1, 2, 3, 4, 5]
console.log (data1);//[2, 3, 4, 5, 6]

3.filter ()
the array element returned by this method is a subset of the called Array. The passed function is used logically to determine whether the function returns TRUE or FALSE.

If the return value is true or a value that can be converted to true, then the element passed to the decision function is a member of that subset, which is added to an array as the return value.

var data = [1,2,3,4,5];
var data1 = data.filter (function (value) {return
 value <= 3;
});

var data2 = data.filter (function (value) {return
 value > 3;
});

Console.log (data); [1, 2, 3, 4, 5]
console.log (data1);//[1,2,3]
console.log (DATA2);/[4,5]

4.every () and some ()
as the name suggests, every () is the array in which the element satisfies the condition specified by the function and returns true; Some () returns True when a certain item is satisfied

var data = [1,2,3,4,5];
var data1 = data.every (function (value) {return
 value < 4;
});

var data2 = data.some (function (value) {return
 value >4;
});

Console.log (data); [1, 2, 3, 4, 5]
console.log (data1);//False
Console.log (DATA2);/True

5.reduce () and Reduceright ()
the two methods combine the array elements using the specified function to generate a single value.

Reduce () has two parameters. The first is the function that performs the simplification operation, that is, to simplify the two values to a value in some way and return the value after the simplification.

The second argument is optional and is used to pass the first parameter function as the initial value. If the second argument is not, the initial value uses the first element value of the array.

var data = [1,2,3,4,5];
var sum = data.reduce (function (a,b) {return
 a+b;
});

var sum1 = data.reduce (function (a,b) {return
 a+b;
},5);

var min = data.reduce (function (a,b) {return
 (a<b) a:b;
});

Console.log (data); [1, 2, 3, 4, 5]
console.log (sum);//
Console.log (sum1);
console.log (min);/1

Sum does not have a second parameter, so the initial value is the first array element, the first step 1+2=3, the second step 3+3=6 ... Last 15.
SUM1 has the second parameter, so the initial value is 5, the first step 5+1=6, the second step 6+2=8 ... Last 20.

Reduceright () is about the same as reduce (), but it handles arrays from high to low (right to left) according to array indices, rather than normal from low to high.

var data = [' A ', ' B ', ' C ']; 
var str = data.reduce (function (x,y) {//sequential return
 x+y;
});

var str1 = data.reduceright (function (x,y) {/reverse return
 x+y;
});

Console.log (data);//[1, 2, 3]
console.log (str);//"abc"
Console.log (STR1);/"CBA"

6.indexOf () and LastIndexOf ()
This method searches the entire array for elements with a given value, returns the index of the found element (one is found, exits), and returns 1 if it is not found.

One from the beginning, one from the tail to the head

var data = [' A ', ' B ', ' A ', ' C ', ' a ']; 

Console.log (Data.indexof (' a ')); 0
Console.log (data.indexof (' d '));//-1
Console.log (Data.lastindexof (' a '));//4

Console.log ( Data.lastindexof (' A ',-2));//2 from the penultimate start
console.log (Data.lastindexof (' A ', 1));//0  from the order of the second forward

7. Array type IsArray ()
to determine if an object is not an array

Console.log (Array.isarray ([]));//true
Console.log (Array.isarray ({}));//false

//Simulate
var isArray1 above = function.isarray| | Function (o) {return
 typeof o = = "Object" &&
  Object.prototype.toString.call (o) = = "[Object Array]";
};

Console.log (IsArray1 ([]));//true
Console.log (IsArray1 ({}));//false
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.