Skip to content
破仑的博客
Go back

JavaScript常用数组迭代方法

JavaScript 数组操作

原文: https://gist.github.com/ljharb/58faf1cfcb4e6808f74aae4ef7944cff

forEach

['zhang', 'zhen', 'qiang'].forEach((val, index, thisArg) => {
    console.log(index, val);
    console.log(thisArg);
});

map:

 const objects = [{ id: 'a', name: 'chengyaojin' }, { id: 'b', name: 'zhangjunhui' }, { id: 'c', name: 'zhangzhenqiang' }];
 const res = objects.map((item, index, list) => {
     item['ctime'] = Date.now();
     return item;
 });

 console.log(res);

filter:

const ints = [1, 2];
const events = ints.filter(item => {
    return item % 2 === 0;
});

console.log(ints === events, events);

reduce:


// 注意:`reduce`和`reduceRight`在`callback`参数后都一个可选的`initalValue`参数,
// 如果忽略不填,则默认是第一项的值
const sum = [1, 2, 3].reduce((result, item) => {
    return result += item;
}, 0);

console.log(sum);

reduceRight: 和reduce相同,只不过遍历的方向是相反的方向

some:

const hasNegativeNumbers = [1, 2, 3, -1, 4].some((item, index) => {
    return item < 0;
});

console.log(hasNegativeNumbers);

every:

const allPositiveNumbers = [1, 2, 3, -1, 4].every((item, index) => {
    return item > 0;
});

console.log(allPositiveNumbers);

find:

 const objects = [{ id: 'a', name: 'chengyaojin' }, { id: 'b', name: 'zhangjunhui' }, { id: 'c', name: 'zhangzhenqiang' }];
 const res = objects.find((item, index, list) => {
     return item.id === 'c';
 });

 console.log(res);

findIndex:

 const objects = [{ id: 'a', name: 'chengyaojin' }, { id: 'b', name: 'zhangjunhui' }, { id: 'c', name: 'zhangzhenqiang' }];
 const res = objects.findIndex((item, index, list) => {
     return item.id === 'c';
 });

 console.log(res);

Share this post on:

Previous Post
Git备忘
Next Post
常用npm包