1. 找出是否有人超過 19 歲?
const people = [
{ name: 'Wes', year: 1988 },
{ name: 'Kait', year: 1986 },
{ name: 'Irv', year: 1970 },
{ name: 'Lux', year: 2015 }
]
function some(arr){
return arr.some(item => (new Date().getFullYear() - item.year) >= 19)
}
2.是否所有人都是成年人
const people = [
{ name: 'Wes', year: 1988 },
{ name: 'Kait', year: 1986 },
{ name: 'Irv', year: 1970 },
{ name: 'Lux', year: 2015 }
]
function every(arr) {
return arr.every(item => (new Date().getFullYear() - item.year) >= 18)
}
3.找到 ID 號為 823423 的評論
const comments = [
{ text: 'Love this!', id: 523423 },
{ text: 'Super good', id: 823423 },
{ text: 'You are the best', id: 2039842 },
{ text: 'Ramen is my fav food ever', id: 123523 },
{ text: 'Nice Nice Nice!', id: 542328 }
];
function find(arr){
return arr.find(item => item.id ===823423 )
}
4.刪除 ID 號為 823423 的評論
const comments = [
{ text: 'Love this!', id: 523423 },
{ text: 'Super good', id: 823423 },
{ text: 'You are the best', id: 2039842 },
{ text: 'Ramen is my fav food ever', id: 123523 },
{ text: 'Nice Nice Nice!', id: 542328 }
];
function findIndex(arr){
return arr.findIndex(item => item.id ===823423)
}
const index = findIndex(comments)
comments.splice(index,1)
5.把數(shù)組的對象元素的某一項拼接成字符串
const goodImgs = [
{url: 'www.hcc.com'},
{url: 'www.yx.com'}
]
var strImages = goodImgs.reduce((str,item)=>{
return str+``
},'')
6.完成下列數(shù)組的常用操作
問題
let todos = [
{
id: 1001,
title: '請找出這個數(shù)組中第一個id為1005的todo的位置',
completed: false
},
{
id: 1002,
title: '請找出這個數(shù)組中所有completed為true的todo',
completed: true
},
{
id: 1005,
title: '這個數(shù)組中todo的completed都是true嗎',
completed: false
},
{
id: 1004,
title: '給所有todo的id加10',
completed: true
},
{
id: 1003,
title: '計算所有todo的id的和',
completed: false
}
]
答案
todos.findIndex((todo) => {
return todo.id === 1005
})
todos.filter((todo) => {
return todo.completed
})
todos.every((todo) => {
return todo.completed
})
todos.map((todo) => {
todo.id+=10
return todo
})
todos.reduce((total,todo) => {
return total+todo.id;
},0)