es6 array methods: 1. map method; 2. find method; 3. findIndex method; 4. filter method; 5. every method; 6. some method; 7. reduce method; 8. reduceRight method; 9. foreach method; 10. keys method, etc.

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
An array is a collection of data of the same data type arranged in a certain order. In the new version of the JavaScript language standard ES6 (ECMAScript 6), ES6 adds some new features to arrays, and these new features expand the ability of arrays to process data. When faced with large data collections, accumulation and filtering can often be completed without looping operations. , conversion and other work. This article will summarize how to use some new features provided by ES6 for arrays.
1. Map method
Processes each element in the array by formulating a method and returns the processed array.
console.clear();
var arr = [12,14,34,22,18];
var arr1 = arr.map((currentValue,index,arr) => {
console.log("当前元素"+currentValue);
console.log("当前索引"+index);
if (currentValue>20) {
return currentValue-10;
} else {
return currentValue-5;
}
})
console.log(arr1)
//另一种形式
let nums = [1, 2, 3];
let obj = {val: 5};
let newNums = nums.map(function(item,index,array) {
return item + index + array[index] + this.val;
//对第一个元素,1 + 0 + 1 + 5 = 7
//对第二个元素,2 + 1 + 2 + 5 = 10
//对第三个元素,3 + 2 + 3 + 5 = 13
}, obj);
console.log(newNums);//[7, 10, 13]
2. Find and findIndex methods
Retrieve elements in the array. The find method returns the first element that meets the requirements, and the findIndex method returns the first element that meets the requirements. element subscript.
console.clear();
var arr = [12,14,34,22,18];
var arr1 = arr.find((currentValue, index) => {
return currentValue>20;
})
var arr2 = arr.findIndex((currentValue, index) => {
return currentValue>20;
})
console.log(arr,arr1,arr2);
//数组元素为对象
var allPeple = [
{name: '小王', id: 14},
{name: '大王', id: 41},
{name: '老王', id: 61}
]
var PId = 14; //假如这个是要找的人的ID
var myTeamArr = [{name: '小王', id: 14}]
function testFunc(item){return item.id == PId ;}
//判断myteam里是不是有这个人,如果==-1 代表没有,在allPeople中找到他,添加入我的队伍
myTeamArr.findIndex(testFunc) == -1
? myTeamArr.push(allPeple.find(testFunc))
: console.log('已存在该人员');
//检索满足条件的对象
var stu = [
{name: '张三', gender: '男', age: 20},
{name: '王小毛', gender: '男', age: 20},
{name: '李四', gender: '男', age: 20}
]
var obj = stu.find((element) => (element.name == '李四'))
console.log(obj);
console.log(obj.name);
[1,2,3].findIndex(function(x) {x == 2;});
// Returns an index value of 1.
[1,2,3].findIndex(x => x == 4);
// Returns an index value of -13. Filter method
Retrieve elements in the array and return all elements that meet the requirements in the form of an array.
console.clear();
var arr = [12,14,34,22,18];
var arr1 = arr.filter((currentValue, index) => {
return currentValue>20;
})
console.log(arr,arr1);
//逻辑属性的筛选
var arr = [
{ id: 1, text: 'aa', done: true },
{ id: 2, text: 'bb', done: false }
]
console.log(arr.filter(item => item.done))
// 保留奇数项
let nums = [1, 2, 3];
let oddNums = nums.filter(item => item % 2);
console.log(oddNums);4. Every method
Detects whether each element in the array meets the conditions. If so, it returns true, otherwise it is false.
console.clear();
var arr = [12,14,34,22,18];
var arr1 = arr.every((currentValue, index) => {
return currentValue>20;
})
console.log(arr,arr1);5. Some method
Detects whether there are elements in the array that meet the conditions. If so, it returns true, otherwise it is false.
console.clear();
var arr = [12,14,34,22,18];
var arr1 = arr.some((currentValue, index) => {
return currentValue>20;
})
console.log(arr,arr1);6, reduce and reduceRight methods
Receive a function as the accumulator (accumulator), each value in the array (from left to right) starts to reduce, Finally a value. reduce accepts a function, which has four parameters: the last value previousValue, the current value currentValue, the index of the current value, and the array array.
The reduceRight method is the same as the reduce method, both find the cumulative number of the array. The difference is that reduceRight() accumulates the array items in the array from the end of the array forward.
When reduceRight() calls the callback function callbackfn for the first time, prevValue and curValue can be one of two values. If reduceRight() is called with an initialValue argument, prevValue is equal to initialValue and curValue is equal to the last value in the array. If the initialValue parameter is not provided, prevValue is equal to the last value in the array and curValue is equal to the second-to-last value in the array.
console.clear();
var arr = [0,1,2,3,4];
var total = arr.reduce((a, b) => a + b); //10
console.log(total);
var sum = arr.reduce(function(previousValue, currentValue, index, array){
console.log(previousValue, currentValue, index);
return previousValue + currentValue;
});
console.log(sum);
//第二个参数为5,第一次调用的previousValue的值就用传入的第二个参数代替
var sum1 = arr.reduce(function(previousValue, currentValue, index){
console.log(previousValue, currentValue, index);
return previousValue + currentValue;
},5);
console.log(sum1);
var sum2 = arr.reduceRight(function (preValue,curValue,index) {
return preValue + curValue;
}); // 10
var sum3 = arr.reduceRight(function (preValue,curValue,index) {
return preValue + curValue;
}, 5); // 15
//计算数组arr的平方和
var arr1 = arr.map((oVal) => {return oVal*oVal;})
console.log(arr1);
var total1 = arr1.reduce((a, b) => a + b); //30
console.log(total1);
//计算指定数组和
let nums = [1, 2, 3, 4, 5];// 多个数的累加
let newNums = nums.reduce(function(preSum,curVal,array) {
return preSum + curVal;
}, 0);
console.log(newNums)//157. foreach method
Loops through the elements of the array, which is equivalent to a for loop and has no return value.
console.clear();
var arr = [12,14,34,22,18];
var arr1 = arr.forEach((currentValue, index) => {
console.log(currentValue, index);
})8. Keys, values, and entries methods
ES6 provides three new methods, entries(), keys() and values(), for traversal array. They all return a traverser object, which can be traversed using a for...of loop. The only difference is that keys() traverses key names, values() traverses key values, and entries() traverses key values. Right traversal.
console.clear();
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"9. Array.from static method
The Array.from() method is mainly used to convert two types of objects (array-like objects) and iterable object [iterable]) into a real array.
console.clear();
//类似数组的对象转为真正的数组
let arrayLike = {
'0': 'a',
'1': 'b',
'2': 'c',
length: 3
}
console.log(Array.from(arrayLike)); // ["a","b","c"]
//字符转数组
let arr = Array.from('w3cplus.com') //字符转数组
console.log(arr); // ["w","3","c","p","l","u","s",".","c","o","m"]
//Set数据转数组
let namesSet = new Set(['a', 'b']) //new Set创建无重复元素数组
let arr2 = Array.from(namesSet); //将Set结构数据转为数组
console.log(arr2); //["a","b"]
//转换Map数据
let m = new Map([[1, 2], [2, 4], [4, 8]]);
console.log(Array.from(m)); // [[1, 2], [2, 4], [4, 8]]
//接受第二个参数为map转换参数
var arr = Array.from([1, 2, 3]); //返回一个原样的新数组
var arr1 = Array.from(arr, (x) => x * x)
console.log(arr1); // [1, 4, 9]
var arr2 = Array.from(arr, x => x * x);
console.log(arr2); // [1, 4, 9]
var arr3 = Array.from(arr).map(x => x * x);
console.log(arr3); // [1, 4, 9]
//大样本生成
var arr4 = Array.from({length:5}, (v, i) => i);
console.log(arr4); // [0, 1, 2, 3, 4]
//第三个参数为diObj对象,map函数中this指向该对象
//该功能实现由对象自带方法转换数据
let diObj = {
handle: function(n){
return n + 2
}
}
console.log(Array.from(
[1, 2, 3, 4, 5],
function (x){return this.handle(x)},
diObj
)) //[3, 4, 5, 6, 7]10. copyWidthin method
The copyWidthin method can copy the array item at the specified position to another position within the current array (the original array item will be overwritten), and then Return the current array. Using the copyWidthin method will modify the current array.
copyWidthin will accept three parameters [.copyWithin(target, start = 0, end = this.length)]:
- target: This parameter is required, from this Position to start replacing array items
- start: This is an optional parameter, starting to read array items from this position, the default is 0, if it is a negative value, it means starting to read from the right to the left of the array
- end: This is an optional parameter. The array item to stop reading at this position is equal to Array.length by default. If it is a negative value, it means the reciprocal
console.clear(); var arr = [1, 2, 3, 4, 5]; //从下标3开始提取2个(5-3=2)元素到下标0 var arr = arr.copyWithin(0, 3, 5); console.log(arr);
11. Fill method
The fill method fills an array with the given value. This method is very convenient for initializing empty arrays. All existing elements in the array will be erased.
The fill method can also accept the second and third parameters, which are used to specify the starting and ending positions of filling.
console.clear();
var arr = ['a', 'b', 'c',,,];
arr.fill(0, 2, 5);
console.log(arr); // ["a", "b", 0, 0, 0]
arr.fill(0, 2);
console.log(arr); // ["a", "b", 0, 0, 0]
arr = new Array(5).fill(0, 0, 3);
console.log(arr); // [0, 0, 0, empty × 2]
arr = new Array(5).fill(0, 0, 5);
console.log(arr); // [0, 0, 0, 0, 0]
console.log(new Array(3).fill({})); //[{…}, {…}, {…}]
console.log(new Array(3).fill(1)); //[1, 1, 1]12. Usage of Set array object
ES6 provides a new data structure Set. It is similar to an array, but the values of the members are unique and there are no duplicate values.
console.clear();
var s = new Set();
[2,3,5,4,5,2,2].forEach(x => s.add(x));
console.log(s); //{2, 3, 5, 4}
for(let i of s) {console.log(i);} //Set对象循环
var set = new Set([1,2,3,4,4]);
//符号”...“将一个数组转为用逗号分隔的参数序列
console.log([...set]); //[1, 2, 3, 4]
var items = new Set([1,2,3,4,5,5,5,5,]);
console.log(items.size); //5,元素个数
// add添加元素
var set = new Set();
set.add("a");
set.add("b");
console.log(set); //{"a", "b"}
var s = new Set();
s.add(1).add(2).add(2); //链式添加
console.log(s.size);
console.log(s.has(1)); //has判断元素1是否存在
console.log(s.has(2)); //true
console.log(s.has(3)); //false
s.delete(2); //删除第2个元素
console.log(s.has(2)); //false
// set转数组
var items = new Set([1,2,3,4,5]);
var array = Array.from(items);
console.log(array); //[1, 2, 3, 4, 5]
// 数组的 map 和 filter 方法也可以间接用于Set
var s = new Set([1,2,3]);
s = new Set([...s].map(x => x * 2));
console.log(s); //{2, 4, 6}
s = new Set([...s].filter(x => (x % 3) ==0));
console.log(s); //6,被3整除
// 实现并集、交集、差集
var a = new Set([1,2,3]);
var b = new Set([4,3,2]);
//并集
var union = new Set([...a, ...b]);
console.log(union);
//交集
var intersect = new Set([...a].filter(x => b.has(x)));
console.log(intersect);
//差集
var difference = new Set([...a].filter(x => !b.has(x)));
console.log(difference);
//遍历数据同步改变原来的Set结构
// 利用原Set结构映射出一个新的结构
var set1 = new Set([1,2,3]);
set1 = new Set([...set1].map(val => val *2));
console.log(set1);
// 利用Array.from
var set2 = new Set([1,2,3]);
set2 = new Set(Array.from(set2, val => val * 2));
console.log(set2);13. Map array object uses
Map object to save key-value pairs, and can remember the original insertion order of keys. Any value (object or primitive) can be used as a key or a value. Map, as a set of key-value pair structures, has extremely fast search speed.
console.clear(); var names = ['Michael', 'Bob', 'Tracy']; var scores = [95, 75, 85]; //Map键值对的结构 var m = new Map([['Michael', 95], ['Bob', 75], ['Tracy', 85]]); console.log(m.get('Michael')); // 95 //初始化Map需要的二维数组 var m = new Map(); // 空Map m.set('Adam', 67); // 添加新的key-value m.set('Bob', 59); console.log(m.has('Adam')); // 是否存在key 'Adam': true m.get('Adam'); // 67 m.delete('Adam'); // 删除key 'Adam' console.log(m.get('Adam')); // undefined //key相同时,后面的值会把前面的值冲掉 var m = new Map(); m.set('Adam', 67); m.set('Adam', 88); console.log(m.get('Adam')) // 88
ES6新版本JavaScript语言给数组添加了许多面向大数据处理的新功能,使得JS在数据处理量和速度方面有了质的提升。需要提示的是,当我们处理的数据量较大时,建议使用Google Chrome浏览器。ES6数组+Chrome浏览器,使得JS在数据处理功能产生变革,完全可以媲美Python或R语言等数据处理软件。
提示:本页中JS脚本代码可复制粘贴到JS代码运行窗口调试体验; 文本编辑快捷键:Ctrl+A - 全选;Ctrl+C - 复制; Ctrl+X - 剪切;Ctrl+V - 粘贴
【推荐学习:javascript高级教程】
The above is the detailed content of What are the array methods in javascript es6. For more information, please follow other related articles on the PHP Chinese website!
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AMThis article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base
JavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AMJavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.
The Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AMThe latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Atom editor mac version download
The most popular open source editor

Dreamweaver CS6
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function







