var divs = document.querySelectorAll('div.pane');
var text = Array.from(divs, (d) => d.textContent);
console.log("div text:", text);
// Old, ES5 way to get array from arguments
function() {
var args = [].slice.call(arguments);
//...
}
// Using ES6 Array.from
function() {
var args = Array.from(arguments);
//..
}
var filled = Array.from([1,,2,,3], (n) => n || 0);
console.log("filled:", filled);
// => [1,0,2,0,3]
ES6 Array方法
数组循环
for循环
使用率最高,也是最基本的一种遍历方式
forEach循环
forEach中传入要执行的回调函数,函数有三个参数。第一个参数为数组元素(必选),第二个参数为数组元素索引值(可选),第三个参数为数组本身(可选)
for in循环
for...in循环可用于循环对象和数组,推荐用于循环对象,可以用来遍历json
for of循环
可循环数组和对象,推荐用于遍历数组。
for...of提供了三个新方法:
key()是对键名的遍历; value()是对键值的遍历; entries()是对键值对的遍历;
map循环
map() 会返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。 map() 方法按照原始数组元素顺序依次处理元素。
map 不修改调用它的原数组本身。
map()中传入要执行的回调函数,函数有三个参数。第一个参数为数组元素(必选),第二个参数为数组元素索引值(可选),第三个参数为数组本身(可选)
数组加一
reduce
array.reduce(function callback(accumulator, currentValue, currentIndex, array){
}[, initialValue])
输出他们的年龄总数
求年龄最大的那个人
filter
filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
演示
组合使用
Array.from()
欢迎评论回复更多你认识的语法糖。