iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 7
0

不知不覺來到了第七天,這次要繼續介紹array的一些方法。

Day7

先建立範例所需要用的資料

const people = [
      { name: 'Wes', year: 1988 },
      { name: 'Kait', year: 1986 },
      { name: 'Irv', year: 1970 },
      { name: 'Lux', year: 2015 }
    ];
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 }
   ];

1.some(),先來看看MDN的解釋:some() 方法會測試陣列中是否至少有一個元素通過由給定之函式所實作的測試。

some()回傳的結果為true或false,但要注意的是陣列裡只要有一個元素符合條件,就會回傳true,全部都不符合條件時才會出現false。

//用new Date().getFullYear()取得現在年份,也就是2018,去減掉people裡的year屬性是否有大於等於19的
//如果有的話,將會回傳true
const isAdult = people.some(person => ((new Date()).getFullYear()) - person.year >= 19);
console.log({isAdult});
//結果為true

2.find(),MDN:find() 方法會回傳第一個滿足所提供之測試函式的元素值。否則回傳 undefined。

find()會回傳第一個符合條件的值,以下為範例

//在comments中尋找是否有id屬性值是823423的元素
const comment = comments.find(comment => comment.id === 823423);
console.log(comment);
//{text: "Super good", id: 823423}

//MDN的範例
var array1 = [5, 12, 8, 130, 44];

var found = array1.find(function(element) {
  return element > 10;
});
//雖然有三個數值都大於10,但第一個符合的是12,所以會回傳12
console.log(found);
// expected output: 12

3.findIndex(),MDN:findIndex() 方法將依據提供的測試函式,尋找陣列中符合的元素,並返回其 index(索引)。如果沒有符合的對象,將返回 -1 。

findIndex跟find蠻相似的,但findIndex回傳的是索引值,要注意索引值是從0開始

//尋找comments第幾個元素的id值符合823423
const index = comments.findIndex(comment => comment.id === 823423);
//1
console.log(index);
 
//MDN範例
var array1 = [5, 12, 8, 130, 44];

function findFirstLargeNumber(element) {
  return element > 13;
}
//雖然44也符合,但130是第一個符合條件的
console.log(array1.findIndex(findFirstLargeNumber));
// expected output: 3

4.slice(),MDN:slice() 方法會回傳一個新陣列物件,為原陣列選擇之 begin 至 end(不含 end)部分的淺拷貝(shallow copy)。而原本的陣列將不會被修改。

slice()執行之後並不會修改原本的陣列,並會回傳修改後的陣列,slice帶有兩個參數,起始點和終點,計算時會以起始點開始終點之前計算,並且都是以索引值0開始

var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
var citrus = fruits.slice(1, 3);
console.log(fruits)
//['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']

console.log(citrus)
//['Orange','Lemon'],從索引值1開始算到3之前,所以實際是抓索引值1跟2的元素

以上就是第七天的內容!


上一篇
JS30-Day6
下一篇
JS30-Day8
系列文
一直想著要做,卻懶得做的JS30系列13
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言