es6新增数组操作方法在我们拿到后端数据的时候,可能会对数据进行一些筛选、过滤,传统的做法如下 // 取出数组中name为kele的数组集合 let a = [ { name: 'kele', title: '可口可乐' }, { name: 'kele', title: '芬达' }, { name: 'hn', title: '红牛' } ] let b = []; for(let i = 0; i < a.length; i++){ if( a[i].name === 'kele' ){ b.push(a[i]) } } console.log(b) //[{name: 'kele', title: '可口可乐'},{name: 'kele', title: '芬达'}] es6中的数组处理方法如下1,Array.filter(callback) let b = a.filter(item => item.name === 'kele'); console.log(b) //[{name: 'kele', title: '可口可乐'},{name: 'kele', title: '芬达'}] Array.filter()让我们摆脱了for循环,代码看起来更加的清爽! 2,Array.find(callback) 这个方法是返回数组中符合条件的第一个元素,否则就返回undefined let a = [1,2,3,4,5]; let b = a.find(item => item > 2); console.log(b) // 3 传入一个回调函数,找到数组中符合搜索规则的第一个元素,返回它并终止搜索 const arr = [1, "2", 3, 3, "2"] console.log(arr.find(item => typeof item === "number")) // 1 3,Array.findIndex(callback) 这个方法是返回数组中符合条件的第一个元素的索引值,否则就返回-1 let a = [1,2,3,4,5]; let b = a.findIndex(item => item > 2); console.log(b) // 2 符合条件的为元素3 它的索引为2 找到数组中符合规则的第一个元素,返回它的下标 const arr = [1, "2", 3, 3, "2"] console.log(arr.findIndex(item => typeof item === "number")) // 0 4.from(),将类似数组的对象(array-like object)和可遍历(iterable)的对象转为真正的数组 const bar = ["a", "b", "c"]; Array.from(bar); // ["a", "b", "c"] Array.from('foo'); // ["f", "o", "o"] 5.of(),用于将一组值,转换为数组。这个方法的主要目的,是弥补数组构造函数 Array() 的不足。因为参数个数的不同,会导致 Array() 的行为有差异。 Array() // [] Array(3) // [, , ,] Array(3, 11, 8) // [3, 11, 8] Array.of(7); // [7] Array.of(1, 2, 3); // [1, 2, 3] Array(7); // [ , , , , , , ] Array(1, 2, 3); // [1, 2, 3] 6、entries() 返回迭代器:返回键值对 const arr = ['a', 'b', 'c']; for(let v of arr.entries()) { console.log(v) } // [0, 'a'] [1, 'b'] [2, 'c'] //Set const arr = newSet(['a', 'b', 'c']); for(let v of arr.entries()) { console.log(v) } // ['a', 'a'] ['b', 'b'] ['c', 'c'] //Map const arr = newMap(); arr.set('a', 'a'); arr.set('b', 'b'); for(let v of arr.entries()) { console.log(v) } // ['a', 'a'] ['b', 'b'] 8.keys() 返回迭代器:返回键值对的key const arr = ['a', 'b', 'c']; for(let v of arr.keys()) { console.log(v) } // 0 1 2 //Set const arr = newSet(['a', 'b', 'c']); for(let v of arr.keys()) { console.log(v) } // 'a' 'b' 'c' //Map const arr = newMap(); arr.set('a', 'a'); arr.set('b', 'b'); for(let v of arr.keys()) { console.log(v) } // 'a' 'b' 9,Array.includes(item, finIndex) includes(),判断数组是否存在有指定元素,参数:查找的值(必填)、起始位置,可以替换 ES5 时代的 indexOf 判断方式。indexOf 判断元素是否为 NaN,会判断错误。 var a = [1, 2, 3]; let bv = a.includes(2); // true let cv = a.includes(4); // false 10,...扩展运算符 可以很方便的帮我们实现合并两个数组 let a = [1,2,3]; let b = [4,5,6]; let c = [...a,...b]; console.log(c) // [1,2,3,4,5,6]; |
|