這次的練習,只有js的陣列方法,所以沒有成品的截圖><
附上個人codepen
const list = [
{
type: "fruit",
name: "banana"
},
{
type: "drink",
name: "cola"
},
{
type: "drink",
name: "tea"
},
];
const haveFruit = list.some((item, index, array) => {
return item.type === "fruit";
})
// item依序為陣列的每一個物件,index為item在陣列中的索引值,array為list陣列本身.index、array參數是可選擇性帶入
console.log(haveFruit); // true
const nums = [1, 2, 3, 4, 5];
const result = nums.some((num) => num > 10);
// 判斷陣列中是否至少有一個數字大於10
console.log(result); // false
const list = [
{
type: "fruit",
name: "banana"
},
{
type: "drink",
name: "cola"
},
{
type: "drink",
name: "tea"
},
];
const isAllFruit = list.every((item, index, array) => {
return item.type === "fruit";
})
console.log(isAllFruit); // false
const food = ["cola", "cookie", "juice", "rice", "bread"];
const whereIsRice = food.findIndex((food, index, array) => {
return food === "rice";
})
// food為遞迴中的元素,item為遞迴中的該元素陣列的索引值,array為要執行方法的此陣列food.
console.log(whereIsRice); // 3
const food = ["cola", "rice", "juice", "rice", "bread"];
const whereIsRice = food.findIndex((food, index, array) => {
return food === "rice";
})
console.log(whereIsRice); // 1
const age = [17, 6, 13, 16, 2];
const result = age.findIndex((item, index, array) => {
return item > 18;
})
console.log(result); // -1
const nums = [1, 12, 3, 49, 25];
const result = nums.find((num, index, array) => {
return num % 2 === 0;
})
console.log(result); // 12
const arr = [
{
name: "jack",
grade: 48,
},
{
name: "marry",
grade: 20,
},{
name: "hank",
grade: 78,
},
]
const result = arr.find((item) => {
return item.grade > 60;
})
console.log(result); // {name: 'hank', grade: 78}
方法真的很多,當你要用的時候,還會想不起來有什麼可以用,這時候問chatGPT最快了哈哈,或是直接將需求整個告訴他,讓他幫你寫程式碼更快XD