Home >Web Front-end >JS Tutorial >javascript Array array common methods_javascript skills
(1) Basic array methods
1.join()
The Array.join() method converts all elements in the array into strings and concatenates them together, returning the final generated string. You can specify the delimiting symbol yourself. If not specified, comma
will be used 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); //长度为10的空数组 组成下边字符串 console.log(a.join("-"));//"---------"
2.reverse()
The Array.reverse() method reverses the order of the elements in the array and returns the array in reverse order (the returned array is itself, the original array has been 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 this
var str = "abcdefg"; console.log(str.split("").reverse().join(""));//"gfedcba" 返回的是新的值 console.log(str); //"abcdefg" 当然了,原始的是不会变的.
3.sort()
The Array.sort() method sorts the elements in the array and returns the sorted array.
When there are no parameters, the default sorting is in order, that is, from small to large. Of course, you can also directly add a comparison function to sort
var arr = [1,4,7]; arr.sort(); console.log(arr); //[1,4,7] arr.sort(function(a,b){ return a-b; //从小到大 }); console.log(arr); //[1,4,7] arr.sort(function(a,b){ return b-a; //从大到小 }); console.log(arr); //[7,4,1] var num = new Array('one','three','Six','Five'); num.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 from which concat() was called and each parameter of concat().
If any of these parameters is itself an array, the elements of the array are concatenated, not the array itself.
But be aware that concat() will not recursively flatten an array of arrays. concat() also does not modify the calling array.
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 slice or subarray of the specified array. Its two parameters specify the starting and ending positions of the segment (a,b) respectively. What is returned is the array elements starting from a to b excluding b.
If there is only one parameter (a), it represents the elements from a to the end of the array.
If a negative number (-a) appears in the parameter, it indicates the position of a relative to the last element in the array. For example (-3) represents the third to last element to the end. If a negative number appears, convert it first, and then find it out according to the range rules
It also returns a 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 general method for inserting or deleting 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 insertion or deletion, and the second parameter specifies the number of elements that should be deleted from the array. If the second parameter is omitted, it will be deleted 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 to be deleted. Any number of arguments that follow specify the elements to be inserted into the array, starting from the position represented by the first argument.
Different from concat() above, splice() directly inserts the array, 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()
Just think of these methods as stack operations: the first two are normal stack operations, and 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 first 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 methods in ECMAScript5
Most of this type of array methods have uniform and general rules. None of them modify the original array.
Most methods receive a function as the first argument and call the function once for each element (or elements) of the array.
If it is a sparse array, the passed function will not be called for elements that do not exist;
In most cases, the function called takes three parameters: the array element, the index of the element, and the array itself. Usually the last two parameters do not need to be filled in.
In addition to the first parameter here (the function), there is a second parameter (it is optional). If the second parameter is present, the called function will be treated as a method with the second parameter.
In other words, the second parameter passed in when calling the function is used as the value of its this keyword.
1.forEach()
This method traverses the array from beginning to end and calls the specified function for each array.
var data = [1,2,3,4,5]; var sum = 0; data.forEach(function(value){ //只使用了第一个参数(函数),调用的函数也只使用了第一个参数数组元素 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){ //调用的函数具有了三个参数 data[item] = value*value; //取平方 }); 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 containing the return value of this 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 elements returned by this method are a subset of the calling array. The function passed is used for logical determination, and 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 judgment function is a member of this subset, and it will be 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()和some()
顾名思义,every()就是数组中所以元素都满足函数指定的条件时 返回true; some()就是某一项满足时就返回 true
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()和reduceRight()
这两个方法使用指定的函数将数组元素进行组合,生成单个值。
reduce()有两个参数。第一个是执行化简操作的函数,就是说用某种方法把两个值化简为一个值,并返回化简后的值。
第二个参数可选,用来传递给第一个参数函数作为初始值。如果第二个参数没有,则初始值就使用数组的第一个元素值。
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);// 15 console.log(sum1);// 20 console.log(min);// 1
sum中没有第二个参数,所以初始值为第一个数组元素,第一步1+2=3,第二步3+3=6... 最后得15
sum1中有第二个参数,所以初始值为5,第一步5+1=6,第二步6+2=8... 最后得20
reduceRight()和reduce()差不多,不同的是它按照数组索引从高到低(从右到左)处理数组,而不是正常的从低到高。
var data = ['a','b','c']; var str = data.reduce(function(x,y){ //顺序 return x+y; }); var str1 = data.reduceRight(function(x,y){ //逆序 return x+y; }); console.log(data);// [1, 2, 3] console.log(str);//"abc" console.log(str1);//"cba"
6.indexOf()和lastIndexOf()
这个方法搜索整个数组中具有给定值的元素,返回找到的元素的索引(找到了一个就退出了),没有找到则返回-1.
一个从头至尾,一个从尾至头
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 从倒数第二个开始 console.log(data.lastIndexOf('a',1));//0 从顺序第二个往前
7.数组类型 isArray()
判断一个对象是不是数组
console.log(Array.isArray([]));//true console.log(Array.isArray({}));//false //模拟上边的 var isArray1 = Function.isArray||function(o){ return typeof o === "object" && Object.prototype.toString.call(o) === "[object Array]"; }; console.log(isArray1([]));//true console.log(isArray1({}));//false