Home > Web Front-end > JS Tutorial > body text

Introduction to unknown array methods in JavaScript

黄舟
Release: 2018-05-15 10:45:52
Original
1437 people have browsed it

This article mainly introduces some array methods that you don’t know about JavaScript. Friends who need it can refer to it

##concat

var a = [1,2,3];
a.concat([4,5,6],7,8);//[1,2,3,4,5,6,7,8]
Copy after login

Note that the a array has not changed, just a new array is returned.

copyWithin

It accepts three parameters.

target (required): The position from which to start replacing data.

start (optional): Start reading data from this position, the default is 0. If it is a negative value, it represents the reciprocal value.
end (optional): Stop reading data before reaching this position. The default is equal to the array length. If it is a negative value, it represents the reciprocal value.

These three parameters should all be numerical values. If not, they will be automatically converted to numerical values

// 将 3 号位复制到 0 号位 
[1, 2, 3, 4, 5].copyWithin(0, 3, 4) 
// [4, 2, 3, 4, 5] 
// -2 相当于 3 号位, -1 相当于 4 号位 
[1, 2, 3, 4, 5].copyWithin(0, -2, -1) 
// [4, 2, 3, 4, 5] 
// 将 3 号位复制到 0 号位 
[].copyWithin.call({length: 5, 3: 1}, 0, 3) 
// {0: 1, 3: 1, length: 5} 
// 将 2 号位到数组结束,复制到 0 号位 
var i32a = new Int32Array([1, 2, 3, 4, 5]); 
i32a.copyWithin(0, 2); 
// Int32Array [3, 4, 5, 4, 5] 
// 对于没有部署 TypedArray 的 copyWithin 方法的平台 
// 需要采用下面的写法 
[].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4); 
// Int32Array [4, 2, 3, 4, 5]
Copy after login

entries

var a = [1,2,3];
var en = a.entries();
en.next().value;//[0.1];
Copy after login

Return an iterable object

every

function isBigEnough(element, index, array) {
 return (element >= 10);
}
var passed = [12, 5, 8, 130, 44].every(isBigEnough);
// passed is false
passed = [12, 54, 18, 130, 44].every(isBigEnough);
// passed is true
Copy after login

Each item returns true through the test function, otherwise it returns false

fill

[1, 2, 3].fill(4)   // [4, 4, 4]
[1, 2, 3].fill(4, 1)   // [1, 4, 4]
[1, 2, 3].fill(4, 1, 2)  // [1, 4, 3]
[1, 2, 3].fill(4, 1, 1)  // [1, 2, 3]
[1, 2, 3].fill(4, -3, -2) // [4, 2, 3]
[1, 2, 3].fill(4, NaN, NaN) // [1, 2, 3]
Array(3).fill(4);   // [4, 4, 4]
[].fill.call({length: 3}, 4) // {0: 4, 1: 4, 2: 4, length: 3}
Copy after login

What changes is the array itself

filter

function isBigEnough(value) {
 return value >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]
Copy after login

Return A new array

find

method returns the value of the first element in the array that satisfies the provided test function. Otherwise return undefind

function isBigEnough(element) {
 return element >= 15;
}
[12, 5, 8, 130, 44].find(isBigEnough); // 130
Copy after login

findIndex

The findIndex() method returns the index of the first element in the array that satisfies the provided test function. Otherwise, -1 is returned.

function isBigEnough(element) {
 return element >= 15;
}
[12, 5, 8, 130, 44].findIndex(isBigEnough); // 3
Copy after login

forEach

let a = ['a', 'b', 'c'];
a.forEach(function(element) {
 console.log(element);
});
// a
// b
// c
//语法
array.forEach(callback(currentValue, index, array){
 //do something
}, this)
array.forEach(callback[, thisArg])
Copy after login

callback

为数组中每个元素执行的函数,该函数接收三个参数:
currentValue(当前值)
数组中正在处理的当前元素。
index(索引)
数组中正在处理的当前元素的索引。
array
forEach()方法正在操作的数组。
thisArg可选
可选参数。当执行回调 函数时用作this的值(参考对象)
Copy after login

Note: There is no way to abort or break out of the forEach loop other than throwing an exception . If you need this, using the forEach() method is wrong and you can use a simple loop instead. If you are testing whether an element in an array meets a certain condition and need to return a boolean value, use Array.every,Array.some. If available, the new methods find() or findIndex() can also be used for early termination of truth tests.

include

arr.includes(searchElement)
arr.includes(searchElement, fromIndex)
Copy after login

Parameters

searchElement

The element value to be found.

fromIndex

Optional

Start searching searchElement

from this index. If negative, the search starts at the index of array.length + fromIndex in ascending order. Default is 0.

Return value

A Boolean.

[1, 2, 3].includes(2);  // true
[1, 2, 3].includes(4);  // false
[1, 2, 3].includes(3, 3); // false
[1, 2, 3].includes(3, -1); // true
[1, 2, NaN].includes(NaN); // true
Copy after login

indexOf

arr.indexOf(searchElement)
arr.indexOf(searchElement[, fromIndex = 0])
Copy after login

Parameters

searchElement

The element to find

fromIndex

The position to start searching. If the index value is greater than or equal to the array length, it means that the search will not be performed in the array and -1 will be returned. If the index value provided in the parameter is a negative value, it is treated as an offset from the end of the array, i.e. -1 means starting from the last element, -2 means starting from the second to last element, and so on. Note: If the index value provided in the parameter is a negative value, the array will still be queried from front to back. If the offset index value is still less than 0, the entire array will be queried. Its default value is 0.

Return value

The index position of the first found element in the array; if not found, -1 is returned

let a = [2, 9, 7, 8, 9]; 
a.indexOf(2); // 0 
a.indexOf(6); // -1
a.indexOf(7); // 2
a.indexOf(8); // 3
a.indexOf(9); // 1
if (a.indexOf(3) === -1) {
 // element doesn't exist in array
}
Copy after login

join

str = arr.join()
// 默认为 ","
str = arr.join("")
// 分隔符 === 空字符串 ""
str = arr.join(separator)
// 分隔符
Copy after login

keys##keys() method returns a new Array iterator that contains The key for each index in the array

let arr = ["a", "b", "c"];
let iterator = arr.keys();
// undefined
console.log(iterator);
// Array Iterator {}
console.log(iterator.next()); 
// Object {value: 0, done: false}
console.log(iterator.next()); 
// Object {value: 1, done: false}
console.log(iterator.next()); 
// Object {value: 2, done: false}
console.log(iterator.next()); 
// Object {value: undefined, done: true}
Copy after login

map The map() method creates a new array whose result is each The result returned after calling a provided function on each element.

let array = arr.map(function callback(currentValue, index, array) { 
 // Return element for new_array 
}[, thisArg])
let numbers = [1, 5, 10, 15];
let doubles = numbers.map((x) => {
 return x * 2;
});
// doubles is now [2, 10, 20, 30]
// numbers is still [1, 5, 10, 15]
let numbers = [1, 4, 9];
let roots = numbers.map(Math.sqrt);
// roots is now [1, 2, 3]
// numbers is still [1, 4, 9]
Copy after login

callback

Function that generates new array elements, using three parameters:

currentValue

The first parameter of the callback, which is being processed in the array the current element.

index

The second parameter of callback is the index of the current element being processed in the array.

array

The third parameter of callback, the array in which the map method is called.

thisArg

Optional. The this value used when executing the callback function.

Return value

A new array, each element is the result of the callback function.

pop and pushThe pop() method removes the last element from the array and returns the value of the element. This method changes the length of the array.

push() method adds one or more elements to the end of the array and returns the new length of the array.

arr.push(element1, ..., elementN)

Merge two arrays

This example uses apply() to add all elements of the second array.

Note that do not use this method to merge arrays when the second array (such as moreVegs in the example) is too large, because in fact there is a limit to the number of parameters a function can accept. For details, please refer to the apply()

var vegetables = ['parsnip', 'potato'];
var moreVegs = ['celery', 'beetroot'];
// 将第二个数组融合进第一个数组
// 相当于 vegetables.push('celery', 'beetroot');
Array.prototype.push.apply(vegetables, moreVegs);
console.log(vegetables); 
// ['parsnip', 'potato', 'celery', 'beetroot']
Copy after login

##reduce and reduceRight

reduce() methods to apply the accumulator and each element in the array (from left to right) applies a function to reduce it to a single value.

array.reduce(function(accumulator, currentValue, currentIndex, array), initialValue)
var total = [0, 1, 2, 3].reduce(function(sum, value) {
 return sum + value;
}, 0);
// total is 6
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
 return a.concat(b);
}, []);
// flattened is [0, 1, 2, 3, 4, 5]
Copy after login

callback

执行数组中每个值的函数,包含四个参数

accumulator

上一次调用回调返回的值,或者是提供的初始值(initialValue)

currentValue

数组中正在处理的元素

currentIndex

数据中正在处理的元素索引,如果提供了 initialValue ,从0开始;否则从1开始

array

调用 reduce 的数组

initialValue

可选项,其值用于第一次调用 callback 的第一个参数。如果没有设置初始值,则将数组中的第一个元素作为初始值。空数组调用reduce时没有设置初始值将会报错。

PS: 与 reduceRight()和reduce() 的执行方向相反

reverse

reverse 方法颠倒数组中元素的位置,并返回该数组的引用。

shift与unshift

shift() 方法从数组中删除第一个元素,并返回该元素的值。此方法更改数组的长度。

unshift() 方法将一个或多个元素添加到数组的开头,并返回新数组的长度。

slice

slice() 方法返回一个从开始到结束(不包括结束)选择的数组的一部分浅拷贝到一个新数组对象。原始数组不会被修改。

arr.slice();
//[0,end];
arr.slice(start);
//[start,end];
arr.slice(start,end);
//[start,end];
Copy after login

slice不修改原数组,只会返回一个浅复制了原数组中的元素的一个新数组。原数组的元素会按照下述规则拷贝:

如果该元素是个对象引用 (不是实际的对象),slice会拷贝这个对象引用到新的数组里。两个对象引用都引用了同一个对象。如果被引用的对象发生改变,则新的和原来的数组中的这个元素也会发生改变。

对于字符串、数字及布尔值来说不是String、Number或者Boolean,slice会拷贝这些值到新的数组里。在别的数组里修改这些字符串或数字或是布尔值,将不会影响另一个数组。

如果向两个数组任一中添加了新元素,则另一个不会受到影响

some

some() 方法测试数组中的某些元素是否通过由提供的函数实现的测试。

const isBiggerThan10 = (element, index, array) => {
 return element > 10;
}
[2, 5, 8, 1, 4].some(isBiggerThan10); 
// false
[12, 5, 8, 1, 4].some(isBiggerThan10); 
// true
Copy after login

toLocaleString与toString

toLocaleString() 返回一个字符串表示数组中的元素。数组中的元素将使用各自的 toLocaleString 方法转成字符串,这些字符串将使用一个特定语言环境的字符串(例如一个逗号 ",")隔开。

var number = 1337;
var date = new Date();
var myArr = [number, date, "foo"];
var str = myArr.toLocaleString(); 
console.log(str); 
// 输出 "1,337,2017/8/13 下午8:32:24,foo"
// 假定运行在中文(zh-CN)环境,北京时区
var a=1234
a.toString()
//"1234"
a.toLocaleString()
//"1,234"
//当数字是四位及以上时,toLocaleString()会让数字三位三位一分隔,像我们有时候数字也会三位一个分号
var sd=new Date()
sd
//Wed Feb 15 2017 11:21:31 GMT+0800 (CST)
sd.toLocaleString()
//"2017/2/15 上午11:21:31"
sd.toString()
//"Wed Feb 15 2017 11:21:31 GMT+0800 (CST)"
Copy after login

splice

splice() 方法通过删除现有元素和/或添加新元素来更改一个数组的内容。

array.splice(start)
array.splice(start, deleteCount) 
array.splice(start, deleteCount, item1, item2, ...)
Copy after login

start

指定修改的开始位置(从0计数)。如果超出了数组的长度,则从数组末尾开始添加内容;如果是负值,则表示从数组末位开始的第几位(从1计数)。

deleteCount 可选

整数,表示要移除的数组元素的个数。如果 deleteCount 是 0,则不移除元素。这种情况下,至少应添加一个新元素。如果 deleteCount 大于start 之后的元素的总数,则从 start 后面的元素都将被删除(含第 start 位)。

如果deleteCount被省略,则其相当于(arr.length - start)。

item1, item2, ... 可选

要添加进数组的元素,从start 位置开始。如果不指定,则 splice() 将只删除数组元素。

返回值

由被删除的元素组成的一个数组。如果只删除了一个元素,则返回只包含一个元素的数组。如果没有删除元素,则返回空数组。

The above is the detailed content of Introduction to unknown array methods in JavaScript. 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