js array method sharing

小云云
Release: 2023-03-21 19:46:02
Original
1018 people have browsed it

Arrays occupy a very important position in js. This article mainly shares the array methods of js with you, hoping to help everyone.

1. Adding and deleting arrays The push() method adds one or more elements to the end of the array

  a = []; 

    a.push(“zero”)     // a = [“zero”] 

    a.push(“one”,”two”) // a = [“zero”,”one”,”two”];
Copy after login

The method to delete an element at the end of the array is the pop() method. The principle is to reduce the length of the array by 1 and return the deleted element.
2. join()

The Array.join() method converts all elements in the array into strings and concatenates them together, returning the final generated string. The default is a comma, and there can be any character in between.

var bb = [‘abc’,’cd’,1,5]; 

    bb.join(“/”)    //”abc/cd/1/5”
Copy after login

The Array.join() method is the reverse operation of the String.split() method, which splits a string into an array.

var str = "abc/cd/1/5";
str.split("/")    //["abc", "cd", "1", "5"]
Copy after login
Copy after login

3. reverse()

Array.reverse() reverses the order of elements in the array,

 var s = [1,2,3]; 

    s.reverse().join(“-“)   //”3-2-1” 
4、sort()
Copy after login

Sort the elements in the array and return the sorted array.
When sort() takes no parameters, it is sorted alphabetically.

 var a = new Array(“banaa”,”apple”,”cherry”); 

    a.sort(); 

    var s = a.join(“/”);   //”apple/banana/cherry”
Copy after login

To sort the array, you need to pass a comparison function. Assuming that the first parameter is first, the comparison function returns a value less than 0,

 var a = [33,4,111,222]; 

    a.sort()   //111,222,33,4 

    a.sort(function(a,b){return a-b});  //4,33,222,111
Copy after login

5. concat()

The Array.concat() method creates and returns a new array. The connected array elements are not the array itself. concat() does not Will modify the called array
var a = [1,2,3];
var b = a.concat(); Copy of array //b = [1,2,3]
a. concat([4,5]); //[1,2,3,4,5]
6, slice()
Array.slice() method returns a fragment or subarray of the specified array, parameters The starting position and ending position

var a = [1,2,3,4,5];
var b = a.slice(0,3)  //[1,2,3]
a.slice(3)        //[4,5]
a.slice(1,-1)      //[2,3,4]
a.slice(-3,-2)     //[3]
Copy after login
Copy after login

7, splice()

The Array.splice() method inserts or deletes elements in the array, which is different from slice() and concat(), and will be modified. array.

  var a = [1,2,3,4,5,6,7,8]; 

    var b = a.splice(4); //a = [1,2,3,4],b=[5,6,7,8] 

    var c = a.slice(1,2)  //a = [1,4] b=[2,3] 

    var a = [1,2,3,4,5]; 

    a.splice(2,0,’a’,’b’)  //a = [1,2,’a’,’b’,3,4,5]
Copy after login

8, push(), pop()

push() adds one or more elements to the end of the array and returns the new length of the array. pop() deletes the last element and returns the deleted element.

 var stack =[]; 

    stack.push(1,2)   //返回2 

    stack.pop()       //返回2 
9、unshift()、shif()
Copy after login

Operate on the head of the array, unshift() adds one or more elements to the head and returns the length, shift() deletes the first element of the array and returns

 var a = []; 

    a.unshift(1,2,3,4)    //a:[1,2,3,4] 返回4 

    a.shift()           //a:[2,3,4]  返回1
Copy after login

Methods of arrays in es5:

Traverse, map, filter, detect, simplify, search arrays
1, forEach()

is from the beginning Traverse the array to the end and call the specified function for each element. The function receives three parameters, array element (value), index (index), and the array itself (arr);

 var data = [1,2,3,4,5]; 

    //每个元素值自加1 

    data.forEach(function(v,i,a){ 

        a[i] = v + 1; 

    }) 

    //[2,3,4,5,6]
Copy after login

2. The map()

map() method passes each element of the called array to the specified function and returns a new array

 a = [1,2,3]; 

    b = a.map(function(x){ 

        return x*x; 

    }) 

    //[1,4,9]
Copy after login

3. filter()

The filter() method performs logical judgment on each element of the array in the transfer function. The function returns true or false
var a = [1,2,3,4,5];
var b = a.filter(function(x){return x < 3}) //[1,2]
4, every() and some()

every() is for all The elements are judged to be true on the transfer function, and some() is judged on one of them.
var a = [1,2,3,4,5];
a.every(function(x){ return x%2 === 0 }) //false, not all values ​​are even numbers
a.some(function(x){
Return x%2 === 0;
}) //true, a contains an even number
5, reduce() and reduceRight()

Combine array elements to generate a single value
var a = [1,2,3,4,5];
var sum = a.reduce(function(x,y){return x+y},0) //Array sum
var product = a.reduce(function(x,y){return x*y},1) //Array product
var max = a.reduce(function(x,y){return (x>y)?x:y}) //Find the maximum value
The reduce() function requires two functions, the first is a function that performs the reduction operation, and the second is the initial value.
6, indexOf() and lastIndexOf()

Search for elements with a given value in the entire array and return the index value of the first element found. If not found, return -1,
var a = [0,1,2,1,0];
a.indexOf(1) //1
a.lastIndexOf(1) //3
a.indexOf(3) //-1
es6 array method
1, Array.of() method, creates an array containing all parameters

let items = Array.of(1,2);//[1,2]
let items = Array.of(2)  //[2]
let items = Array.of("2")//["2"]
Copy after login
Copy after login

2, Array.from(), Convert non-array objects into formal arrays
3. find() and findIndex() receive two parameters, one is a callback function and the other is an optional parameter. find() returns the found value and findeIndex() returns Find the index value,

let number = [25,30,35,40,45]
console.log(number.find(n => n > 33)) //35
console.log(number.findIndex(n => n >33)) //2
Array deduplication

1、遍历数组去重function unique(obj){
    var arr = [];    var len = obj.length;    for(var i=0;i<len;i++){        if(arr.indexOf(obj[i]) == -1){
            arr.push(obj[i])
        }
    }    return arr;
}
unique([1,1,1,2,3])
[1,2,3]2、对象键值对法function unique(obj){
    var tar = {},arr = [],len = obj.length,val,type;    for(var i = 0;i<len;i++){        if(!tar[obj[i]]){
            tar[obj[i]] = 1;
            arr.push(obj[i])
        }
    }    return arr;
}3、es6 new Set()方法Array.from(new Set([1,2,3,3,3])) //[1,2,3]1.
Copy after login
Copy after login

           

1.数组的添加和删除 push()方法在数组的尾部添加一个或者多个元素
a = [];
a.push(“zero”) // a = [“zero”]
a.push(“one”,”two”) // a = [“zero”,”one”,”two”];
在数组的尾部删除一个元素方法是pop()方法,原理是使数组的长度减少1,并返回被删除的元素。
2、join()

Array.join()方法将数组中的所有的元素转化为字符串并连接一起,返回最后生成的字符串。默认是是逗号,中间可以是任意的字符。
var bb = [‘abc’,’cd’,1,5];
bb.join(“/”) //”abc/cd/1/5”
Array.join()方法是String.split()方法的逆向操作,后者是将字符串分割成数组。

var str = "abc/cd/1/5";
str.split("/")    //["abc", "cd", "1", "5"]
Copy after login
Copy after login

3、reverse()

Array.reverse()将数组中的元素顺序颠倒,
var s = [1,2,3];
s.reverse().join(“-“) //”3-2-1”
4、sort()

对数组中的元素进行排序,返回排序后的数组。
当sort()不带参数时,是按字母表排序。
var a = new Array(“banaa”,”apple”,”cherry”);
a.sort();
var s = a.join(“/”); //”apple/banana/cherry”
进行数组排序,要传递一个比较函数,假设第一个参数在前,比较函数返回一个小于0的数值,
var a = [33,4,111,222];
a.sort() //111,222,33,4
a.sort(function(a,b){return a-b}); //4,33,222,111
5、concat()

Array.concat()方法创建并返回一个新数组,连接的数组元素,不是数组本身,concat()不会修改调用的数组
var a = [1,2,3];
var b = a.concat(); 数组的复制//b = [1,2,3]
a.concat([4,5]); //[1,2,3,4,5]
6、slice()
Array.slice()方法返回制定数组的一个片段或子数组,参数时开始位置、结束位置

var a = [1,2,3,4,5];
var b = a.slice(0,3)  //[1,2,3]
a.slice(3)        //[4,5]
a.slice(1,-1)      //[2,3,4]
a.slice(-3,-2)     //[3]
Copy after login
Copy after login

7、splice()

Array.splice()方法在数组中插入或删除元素,不同于slice(),concat(),会修改数组。

 var a = [1,2,3,4,5,6,7,8]; 

    var b = a.splice(4); //a = [1,2,3,4],b=[5,6,7,8] 

    var c = a.slice(1,2)  //a = [1,4] b=[2,3] 

    var a = [1,2,3,4,5];
Copy after login

a.splice(2,0,’a’,’b’) //a = [1,2,’a’,’b’,3,4,5]
8、push()、pop()

push()在数组的尾部添加一个或者多个元素,并返回数组的新的长度。pop()删除最后一个元素,返回删除的元素。
var stack =[];
stack.push(1,2) //返回2
stack.pop() //返回2
9、unshift()、shif()

在数组的头部进行操作,unshift()在头部添加一个或多个元素,返回长度,shift()删除数组的第一个元素,并返回
var a = [];
a.unshift(1,2,3,4) //a:[1,2,3,4] 返回4
a.shift() //a:[2,3,4] 返回1
es5中数组的方法:

遍历、映射、过滤、检测、简化、搜索数组
1、forEach()

是从头至尾遍历数组,为每个元素调用制指定的函数,该函数接收三个参数,数组元素(value)、索引(index)、数组本身(arr);
var data = [1,2,3,4,5];
//每个元素值自加1
data.forEach(function(v,i,a){
a[i] = v + 1;
})
//[2,3,4,5,6]
2、map()

map()方法将调用的数组的每一个元素传递给指定的函数,返回一个新数组
a = [1,2,3];
b = a.map(function(x){
return x*x;
})
//[1,4,9]
3、filter()

filter()方法是对数组的每一个元素的,在传递函数中进行逻辑判断,该函数返回true、false
var a = [1,2,3,4,5];
var b = a.filter(function(x){return x < 3}) //[1,2]
4、every()和some()

every()是对所有的元素在传递函数上进行判断为true,some()是对其中的一个进行判断。
var a = [1,2,3,4,5];
a.every(function(x){ return x%2 === 0 }) //false,不是所有的值都是偶数
a.some(function(x){
return x%2 === 0;
}) //true,a含有偶数
5、reduce()和reduceRight()

将数组元素进行组合,生成单个值

var a = [1,2,3,4,5]; 

    var sum = a.reduce(function(x,y){return x+y},0)  //数组求和 

    var product = a.reduce(function(x,y){return x*y},1) //数组求积 

    var max = a.reduce(function(x,y){return (x>y)?x:y})  //求最大值 

    reduce()函数需要两个函数,第一个是执行简化操作的函数,第二个是初始值。
Copy after login

6、indexOf()和lastIndexOf()

搜索整个数组中给定的值的元素,返回找到的第一个元素的索引值,没有找到返回-1,

 var a = [0,1,2,1,0]; 

    a.indexOf(1)  //1 

    a.lastIndexOf(1) //3 

    a.indexOf(3)  //-1
Copy after login

es6数组方法
1、Array.of()方法,创建一个包含所有参数的数组

let items = Array.of(1,2);//[1,2]
let items = Array.of(2)  //[2]
let items = Array.of("2")//["2"]
Copy after login
Copy after login

2、Array.from(),将非数组对象转换为正式数组
3、find()和findIndex()接收两个参数,一个是回调函数,另一个是可选参数,find()返回查找到的值,findeIndex()返回查找到的索引值,

let number = [25,30,35,40,45]
console.log(number.find(n => n > 33)) //35
console.log(number.findIndex(n => n >33)) //2
数组去重

1、遍历数组去重function unique(obj){
    var arr = [];    var len = obj.length;    for(var i=0;i<len;i++){        if(arr.indexOf(obj[i]) == -1){
            arr.push(obj[i])
        }
    }    return arr;
}
unique([1,1,1,2,3])
[1,2,3]2、对象键值对法function unique(obj){
    var tar = {},arr = [],len = obj.length,val,type;    for(var i = 0;i<len;i++){        if(!tar[obj[i]]){
            tar[obj[i]] = 1;
            arr.push(obj[i])
        }
    }    return arr;
}3、es6 new Set()方法Array.from(new Set([1,2,3,3,3])) //[1,2,3]1.
Copy after login
Copy after login

相关推荐:

vue.js数组更新实例分享

JS数组去重方法总结

js数组常用的一些排序法

The above is the detailed content of js array method sharing. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template