Home Web Front-end JS Tutorial Introduction to unknown array methods in JavaScript

Introduction to unknown array methods in JavaScript

May 15, 2018 am 10:45 AM
javascript js

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

See all articles