Home >Web Front-end >JS Tutorial >What are the array methods in javascript es6
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.
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]
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 -1
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);
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);
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);
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)//15
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); })
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"
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]
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)]:
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);
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]
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);
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!