JS数组的迭代
栏目: JavaScript · 发布时间: 7年前
内容简介:forEach() 方法对数组的每个元素执行一次提供的函数。forEach()是没有办法中止或者跳出循环的,除非抛出一个异常。map() 方法创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。
forEach
forEach() 方法对数组的每个元素执行一次提供的函数。
var array1 = ['a', 'b', 'c'];
array1.forEach(function(element) {
console.log(element);
});
// expected output: "a"
// expected output: "b"
// expected output: "c"
forEach()是没有办法中止或者跳出循环的,除非抛出一个异常。
map
map() 方法创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。
var array1 = [1, 4, 9, 16]; // pass a function to map const map1 = array1.map(x => x * 2); console.log(map1); // expected output: Array [2, 8, 18, 32]
map()与forEach()的区别是map返回一个循环处理后的数组,不改变原数组的值,而forEach则只是遍历一遍数组,执行提供的函数。
for of
for...of语句在可迭代对象(包括 Array,Map,Set,String,TypedArray,arguments 对象等等)上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句
let iterable = [10, 20, 30];
for (const value of iterable) {
console.log(value);
}
// 10
// 20
// 30
关于for...of语句遍历更多用法 mdn
filter
filter() 方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。
var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present']; const result = words.filter(word => word.length > 6); console.log(result); // expected output: Array ["exuberant", "destruction", "present"]
reduce
reduce() 方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。
const array1 = [1, 2, 3, 4]; // 1 + 2 + 3 + 4 console.log(array1.reduce((accumulator, currentValue) => accumulator + currentValue)); // expected output: 10
every
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
some
some() 方法测试是否至少有一个元素通过由提供的函数实现的测试。
对于放在空数组上的任何条件,此方法返回false。
[2, 5, 8, 1, 4].some(x => x > 10); // false [12, 5, 8, 1, 4].some(x => x > 10); // true
以上所述就是小编给大家介绍的《JS数组的迭代》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Inside Larry's and Sergey's Brain
Richard Brandt / Portfolio / 17 Sep 2009 / USD 24.95
You’ve used their products. You’ve heard about their skyrocketing wealth and “don’t be evil” business motto. But how much do you really know about Google’s founders, Larry Page and Sergey Brin? Inside......一起来看看 《Inside Larry's and Sergey's Brain》 这本书的介绍吧!