anjia / blog

博客,积累与沉淀
107 stars 4 forks source link

数组遍历 #12

Open anjia opened 6 years ago

anjia commented 6 years ago

for > for-of > forEach > filter > map > for-in every > some

const arr = [1,2,3,4,5];
// const arr = [{'name': 'anjia', 'score': { 'math':90, 'eng':100}}, 5, 'test'];

function log(msg, prefix){
    prefix ? console.log('\n' + msg) : console.log(msg);

}

log('for', true);
for(let i=0, len=arr.length; i<len; i++){
    log(arr[i]);
}

log('for-of', true);
for(let item of arr){
    log(item);
}

log('forEach', true);
arr.forEach(item => {
    log(item);
});

log('for-in', true);
for(i in arr){  // 下标
    log(arr[i]);
}
function log(msg, prefix){
    prefix ? console.log('\n'+msg) : console.log(msg);
}

log('map', true);
var arr = [1,2,3,4,5];
var newArr = arr.map(item => {
    log(item);
    return item*2;
});
log(newArr);

log('filter', true);
var arr = [1,2,3,4,5,6];
let greater = arr.filter(item =>{
    log(item);
    return item > 3;
});
log(arr);
log(greater);

log('reduce', true);
let scores = [10, 20, 30];
let total = scores.reduce((sum, item)=>{
    console.log('sum=', sum, '  item=', item);
    return sum + item;
}, 0);
log(total);
anjia commented 6 years ago

e.g.

const members = ['anjia', 'luoqiang', 'lijianchun'];

// 移除'anjia'
const withoutAnjia = members.filter(item => item!=='anjia');
console.log(withoutAnjia === members);   // false
console.log(withoutAnjia, members);

// 把'anjia'替换成'zora'
const replaceAnjia = members.map(item => item==='anjia'?'zora':item);
console.log(replaceAnjia === members);  // false
console.log(replaceAnjia, members);

// 把所有人名大写
const strongMembers = members.map(item => item.toUpperCase());
console.log(strongMembers === members);   // false
console.log(strongMembers, members);

// 和另外一组进行合并
const otherMembers = ['peipei', 'yingying'];
const newMembers = [...members, ...otherMembers];
console.log(newMembers === members, newMembers === otherMembers); // false, false
console.log(newMembers, members);