【JavaScript】——JS array method (full and detailed)

1. Create an array

1. Use the array literal method

var arr1 = [];     // 创建一个数组
var arr2 = [10];   // 创建一个数组长度为10的数组
var arr3 = ['a','b','c'];  // 创建一个包含3个字符串的数组

2. Use the Array constructor

No parameter construction

var arr1 = new Array();   // 创建一个空数组

Construct with parameters

If only one numeric parameter is passed, it means to create an empty array with the initial length of the specified array

var arr2 = new Array(10);     // 创建一个数组长度为10的数组

If a non-numeric parameter is passed in or the parameter is greater than 1, it means to create an array containing the specified elements

var arr3 = new Array('a','b','c');     // 创建一个包含3个字符串的数组

3. The Array.of method creates an array (new in es6)

The Array.of() method creates an array containing all incoming parameters, regardless of the number and type of parameters

let arr1 = Array.of(1,2);
console.log(arr1.length);   // 2

let arr2 = Array.of(3);
console.log(arr2.length);   // 1
console.log(arr2[0]);   // 3

4. The Array.from method creates an array (new in es6)

Converting non-array objects to real arrays in js is very cumbersome. In es6, pass an iterable object or an array-like object as the first parameter, and Array.from() can return an array

function arga(...args){  // ...args剩余参数数组,由传递给函数的实际参数提供
     let arg = Array.from(args);
     console.log(arg);
}

arga(arr1,26,from);     // [arr1,26,from]

2. Array method

1. The method of changing the array itself

push , add an element to the end of the array, one or more elements can be added, and the return value is the changed length value of the array

pop , delete an element from the end of the array, the return value is the deleted element

var arr1 = ['lily','lucy','Tom'];
var count = arr1.push('Jack','Sean');
console.log(count);   // 5
console.log(arr1);   // ['lily','lucy','Tom','Jack','Sean']

var item = arr1.pop();
console.log(item);   // Sean
console.log(arr1);   // ['lily','lucy','Tom','Jack']

unshift , add one or more elements to the head of the array, the return value is the changed length value of the array
shift , delete the first element from the head of the array, and the return value is the deleted element

var arr1 = ['lily','lucy','Tom'];
var count = arr1.unshift('Jack','Sean');
console.log(count);   // 5
console.log(arr1);   // ['Jack','Sean','lily','lucy','Tom']

var item = arr1.shift();
console.log(item);   // Jack
console.log(arr1);   // [''Sean','lily','lucy','Tom']

splice(index, num, item1, item2, …) , index specifies the index position to start processing, and num specifies how many items to delete, starting from the third element is a new element item. It can realize adding, deleting and replacing elementsfrom the specified index positionThe return value is an array of removed elements.

//替换
var a=['a','b','c'];
var b=a.splice(1,1,'e','f');    //a=['a','e','f','c'],b=['b']

//删除
var arr1 = [1,3,5,7,9,11];
var arrRemoved = arr1.splice(0,2);
console.log(arr1);   // [5,7,9,11]
console.log(arrRemoved);   // [1,3]

// 添加元素
var arr1 = [22,3,31,12];
arr1.splice(1,0,12,35);
console.log(arr1);   // [22,12,35,3,31,12]

sort , sort the array, in ascending order by default, you can pass parameters of the function type to determine the sorting method

Used to sort the elements of an array. The sort order can be alphanumeric and ascending or descending, the default sort order is alphabetically ascending

var arr1 = ['a','d','c','b'];
console.log(arr1.sort());   // ['a','b','c','d']

function compare(value1,value2){
     if(value1 < value2){
          return -1;
     }else if(value1 > value2){
          return 1;
     }else{
          return 0;
     }
}

var arr2 = [13,24,51,3];
console.log(arr2.sort(compare));   // [3,13,24,51]

// 如果需要通过比较函数产生降序排序的结果,只要交后比较函数返回的值即可

reverse , reverse the array

var arr1 = [13,24,51,3];
console.log(arr1.reverse());   // [3,51,24,13]
console.log(arr1);   // [3,51,24,13](原数组改变)

The reduce() method accepts a function as an accumulator, and each value in the array (from left to right) is initially reduced to a final value.

var arr1 = [1,2,3,4,5];
var sum = arr1.reduce((prev,cur,index,array) => {
     return prev + cur;
},10);   // 数组一开始加了一个初始值10,可以不设默认0
console.log(sum);   // 25

2. The method of returning a new array without changing the array itself

concat , the parameter of concat, can be a single/multiple values ​​of basic types, or an array. Concatenate the original array and parameters, and return the new array formed after splicing.

var arr1 = [1,3,5,7];
var arrCopy = arr1.concat(9,[11,13]);
console.log(arrCopy);   // [1,3,5,7,9,11,13]
console.log(arr1);   // [1,3,5,7](原数组未被修改)

slice(startIndex, endIndex) , intercept the fragment of the original array, close the front and open the interval, start to intercept the element containing the startIndex index, until the element before the endIndex index

Interception interval: [startIndex, endIndex)

var arr1 = [1,3,5,7,9,11];
var arrCopy = arr1.slice(1);
var arrCopy2 = arr1.slice(1,4);
var arrCopy3 = arr1.slice(1,-2);   // 相当于arr1.slice(1,4);
var arrCopy4 = arr1.slice(-4,-1);   // 相当于arr1.slice(2,5);
console.log(arr1);   // [1,3,5,7,9,11](原数组没变)
console.log(arrCopy);   // [3,5,7,9,11]
console.log(arrCopy2);   // [3,5,7]
console.log(arrCopy3);   // [3,5,7]
console.log(arrCopy4);   // [5,7,9]

//如果不传入参数二,那么将从参数一的索引位置开始截取,一直到数组尾
var a=[1,2,3,4,5,6];
var b=a.slice(0,3);    //[1,2,3]
var c=a.slice(3);       //[4,5,6]
 
//如果两个参数中的任何一个是负数,array.length会和它们相加,试图让它们成为非负数,举例说明:
//当只传入一个参数,且是负数时,length会与参数相加,然后再截取
var a=[1,2,3,4,5,6];
var b=a.slice(-1);    //[6]
 
//当只传入一个参数,是负数时,并且参数的绝对值大于数组length时,会截取整个数组
var a=[1,2,3,4,5,6];
var b=a.slice(-6);    //[1,2,3,4,5,6]
var c=a.slice(-8);    //[1,2,3,4,5,6]
 
//当传入两个参数一正一负时,length也会先于负数相加后,再截取
var a=[1,2,3,4,5,6];
var b=a.slice(2,-3);    //[3]
 
//当传入一个参数,大于length时,将返回一个空数组
var a=[1,2,3,4,5,6];
var b=a.slice(6);  //[]

3. Loop through related methods

These methods can also indirectly change the elements of the array itself during the loop

forEach ((item, index) => {}) method, traverses each element of the array, the parameter is a function, and the two parameters of the parameter function are the array item and the corresponding index

The function callback in the forEach method has three parameters:

The first parameter is the content of the array to traverse ,

The second parameter is the corresponding array index ,

The third parameter is the array itself

var arr = [1,2,3,4];
var sum =0;
arr.forEach(function(value,index,array){

 array[index] == value; //结果为true

 sum+=value; 

 });

console.log(sum); //结果为 10

The includes() method, newly added by es7, is used to judge whether an array or string contains a specified value, use the === operator to compare values, if it returns true, otherwise false, there are two parameters, the first The first is (required) the value of the element to be searched for, and the second is (optional) the position at which to start looking for the element.

var arr1 = [22,3,31,12,58];
var includes = arr1.includes(31);
console.log(includes);   // true

var includes2 = arr1.includes(31,3);   // 从索引3开始查找31是否存在
console.log(includes2);   // false

The map((item, index) => {}) method traverses each element of the array. The parameter is a function. The two parameters of the parameter function are the array item and the corresponding index. According to the execution results of the parameter function, these results are Form a new array to return.

Elements are processed sequentially in the order of the original array elements.

let array = [1, 2, 3, 4, 5];

let newArray = array.map((item) => {
    return item * item;
})

console.log(newArray)  // [1, 4, 9, 16, 25]

The filter((item, index) => {}) method traverses each element of the array, executes the parameter function, and leaves those items that meet the conditions defined in the parameter function to form a new array and return

const array = [14, 17, 18, 32, 33, 16, 40];
const newArr = array.filter(num => num > 14)
console.log(newArr);//打印 [17,18,32,33,16,40]
 
// 查找某个值-------------------------
const array = [14, 17, 18, 32, 33, 16, 40];
const newArr = array.filter(num => num == 14)
console.log(newArr);//打印 [14]
 
//返回大于某个值和小于某个值的元素
const array = [14, 17, 18, 32, 33, 16, 40];
const newArr = array.filter(num => num > 14 && num < 33)
console.log(newArr);//打印 [17, 18, 32, 16]

find() and findIndex()

Both accept two parameters: a callback function, and an optional value used to specify this inside the callback function

The callback function can accept 3 parameters: an element of the array, the index position corresponding to the element, and the array itself, and stop searching when the callback function returns true for the first time.

The difference between the two is that the find() method returns the matching value, while the findIndex() method returns the index of the matching position
 

let arr = [1,2,3,4,5];
let num = arr.find(item => item > 1);
console.log(num) // 2

let arr = [1,2,3,4,5];
let num = arr.findIndex(item => item > 1);
console.log(num) // 1

entries()、keys()和values()

ES6 adds entries(), keys() and values()--for traversing arrays. They all return a traverser object, which can be traversed with the for...of loop. The difference is that keys() traverses the key names, values() traverses the key values, and entries() traverses the

Traversal of key-value pairs

for(let index of [a,b].keys()){
     console.log(index);
}
// 0
// 1

for(let elem of [a,b].values()){
     console.log(elem);
}
// a
// b

for(let [index,elem] of [a,b].entries()){
     console.log(index,elem);
}
// 0 'a'
// 1 'b'

If you don't use the for...of loop, you can manually call the next method of the traverser object to traverse

let arr1 = [a,b,c];
let entries = arrr1.entries();
console.log(entries.next().value);   // [0,a]
console.log(entries.next().value);   // [1,b]
console.log(entries.next().value);   // [2,c]

indexOf()

The indexof method can be used on strings and arrays.
The indexOf() method returns the first occurrence of a specified string value in a string or an array.
 

    arr = ['mfg', '2017', '2016'];

    console.log(arr.indexOf('mfg')); // 0
    console.log(arr.indexOf('m')); // -1
    console.log(arr.indexOf('2017'));// 1
    console.log(arr.indexOf(2017)); // -1,这里不会做隐式类型转换

some((item, index) => {}) method, loops the array, executes the condition in the parameter function for each item, returns true immediately if there is an item that meets the condition, and does not continue traversing; if it has not been found after traversing all Returns false if it matches

Determine whether there is an item in the array that satisfies the condition, as long as there is an item that meets the condition, it will return true.

var arr1 = [1,2,3,4,5];
var arr2 = arr1.some(x => {
     return x < 3;
});
console.log(arr2);   // true

var arr3 = arr1.some(x => {
     return x < 1;
});
console.log(arr3);   // false

every((item, index) => {}) Contrary to some, every needs to return true if each item in the array meets the conditions in the parameter function, and returns false immediately if any item does not meet, and no longer Continue to iterate over subsequent items.

Determine whether each item in the array satisfies the condition, and only returns true if all items meet the condition.

var arr1 = [1,2,3,4,5];
var arr2 = arr1.every(x => {
     return x < 10;
});
console.log(arr2);   // true

var arr3 = arr1.every(x => {
     return x < 3;
});
console.log(arr3);   // false

4. Other array methods

join() : Join each item of the array into a string with the specified delimiter

The join() method is used to convert all the elements in the array into a string , and commas are used as separators by default

var arr1 = [1,2,3];
console.log(arr1.join());   // 1,2,3
console.log(arr.join('-'));   // 1-2-3
console.log(arr);   // [1,2,3](原数组不变)

Both toLocaleString() and toString() convert arrays to strings

var arr1 = [22,3,31,12];
let str = arr1.toLocaleString();
var str2 = arr1.toString();

console.log(str);   // 22,3,31,12
console.log(str2);   // 22,3,31,12

Guess you like

Origin blog.csdn.net/qq_50497708/article/details/128216125