【JavaScript 教程】第六章 数组17—flatMap() :对每个元素执行映射函数并将结果展平
let newArray = arrayObject.flatMap(callback,thisArg);
function callback(currentValue [[,index], array]);
let sentences = ["JavaScript Array flatMap()", " ", "is", " ", "Awesome"];
let words = sentences.map(s => s.split(' '));
console.log(words);
[
[ 'JavaScript', 'Array', 'flatMap()' ],
[ ' ' ],
[ 'is' ],
[ ' ' ],
[ 'Awesome' ]
]
let sentences = [
"JavaScript Array flatMap()",
" ",
"is",
" ",
"Awesome"
];
let words = sentences.flatMap(s => s.split(' '));
console.log(words);代码语言:JavaScript (javascript )
[ 'JavaScript', 'Array', 'flatMap()', '', '', 'is', '', '', 'Awesome' ]
let cart = [{
name: 'Smartphone',
qty: 2,
price: 500,
freeOfCharge: false
},
{
name: 'Tablet',
qty: 1,
price: 800,
freeOfCharge: false
}
];
let newCart = cart.flatMap(
(item) => {
if (item.name === 'Smartphone') {
return [item, {
name: 'Screen Protector',
qty: item.qty,
price: 5,
freeOfCharge: true
}]
} else {
return [item];
}
}
);
console.log(newCart);
[
{ name: 'Smartphone', qty: 2, price: 500, freeOfCharge: false },
{ name: 'Screen Protector', qty: 2, price: 5, freeOfCharge: true },
{ name: 'Tablet', qty: 1, price: 800, freeOfCharge: false }
]
const total = newCart.reduce((sum, item) => {
if (!item.freeOfCharge)
sum += item.price * item.qty;
return sum;
}, 0);
console.log({total});
{ total: 1800 }
学习更多技能
请点击下方公众号
评论