JavaScript 陣列處理方法map(), every(), some(), reduce() filter(), find(), forEach(),

陣列定義:
陣列就是一個「有序」、「有索引」、「有值」的一個「集合」。
是由一對中括號 [ ] 組成, [ ] 裡面為陣列元素,每個元素以逗號分開,
可以是純數組,或者數組對象。

map

map沒有返回值,適合用在對陣列進行 ‘修改’ 時
不影响原有的数组大小;
接受一個 callback 函式,callback 可以有三個參數( currentValue, index, array),

  • currentValue 代表目前處理到的元素的值
  • index 代表目前處理到的元素的索引
  • array 代表陣列本身

map在數值是單一簡單類型時,並不會改變數組

const arr = [1, 2, 3]
const result = arr.map(item => {
  item = item * 3;
  return item;
});
console.log('arr', arr);     // [1, 2, 3]
console.log('result', result);  // [3, 6, 9]

在數值是對象複雜類型時,若是透過’直接’賦值的方式則會改變原數組

const arr = [
  { data: 1 },
  { data: 1 },
  { data: 1 }
]
const result = arr.map(item => {
  item.data= item.data+ 2;  
  return item
});
console.log('arr', arr);  //原数组被改变,所有item下的data都等于3
/*const arr = [
  { data: 3 },
  { data: 3 },
  { data: 3 }
]*/

一般情況下不建議改變原數組而是另外賦值給新數組。若不想改變原數組則可以使用以下:

const arr = [
  { data: 1 ,id:2},
  { data: 1 ,id:3},
  { data: 1 ,id:4}
]
const newArry= arr.map(item => ({
  ...item,//es6省略符號 相當於 id:item.id
  data: item.data+ 2 //不直接通过item.data = item.data+ 2
}));
console.log('arr', arr);
console.log('newArry', newArry);

filter

filter 不会改变原数组,它返回过滤后的新数组。遍歷一個陣列中的每個元素,很適合用在過濾符合條件時
只能用return返回其結果,並在後面的條件中,為true的加入新數組,false則移除數組
接受一個 callback 函式,callback 可以有三個參數(element, index, array),

  • element:陣列元素的值。
  • index:陣列元素的所在位置。
  • arr:已經過 filter 處理的陣列

var numbers=[20, 10, 9, 25, 1, 3, 8, 11]; 
var result=numbers.filter(function(element, index, arr){ 
return element >= 10; 
}); 
console.log(result); // [20, 10, 25, 11]

如果是更複雜的判斷式時顯然一句代碼式沒辦法滿足需求的,這時候可以新增一個封裝,用來判斷複雜條件,最終return true或false即可:

var arr = [
  { id: 15 },
  { id: -1 },
  { id: 0 },
  { id: 3 },
  { id: 12.2 },
  { },
  { id: null },
  { id: NaN },
  { id: 'undefined' }
];
var arr = [
  { id: 15 },
  { id: -1 },
  { id: 0 },
  { id: 3 },
  { id: 12.2 },
  { },
  { id: null },
  { id: NaN },
  { id: 'undefined' }
];

var invalidEntries = 0;

function isNumber(obj) {
  return obj !== undefined && typeof(obj) === 'number' && !isNaN(obj);
}

function filterByID(item) {
  if (isNumber(item.id) && item.id !== 0) {
    return true;
  } 
  invalidEntries++;
  return false; 
}

var arrByID = arr.filter(filterByID);

console.log('Filtered Array\n', arrByID); 
// Filtered Array
// [{ id: 15 }, { id: -1 }, { id: 3 }, { id: 12.2 }]

console.log('Number of Invalid Entries = ', invalidEntries); 
// Number of Invalid Entries = 5

every

every() 可以檢查所有的陣列是否符合條件,這僅會回傳一個值 true or false,可以用來檢查陣列中的內容是否符合特定條件。
接受一個 callback 函式,callback 可以有三個參數(item, index, array),

  • element:陣列元素的值。
  • index:陣列元素的所在位置。
  • arr:陣列
var array = [
  {
    name: 'Casper',
    like: '鍋燒意麵',
    age: 18
  },
  {
    name: 'Wang',
    like: '炒麵',
    age: 24
  },
  {
    name: 'Bobo',
    like: '蘿蔔泥',
    age: 1
  },
  {
    name: '滷蛋',
    like: '蘿蔔泥',
    age: 3
  }
];

var ans = array.every(function(item, index, array){
  console.log(item, index, array); // 物件, 索引, 全部陣列
  return item.age > 10 // 當全部 age 大於 10 才能回傳 true
});
console.log(ans); // false: 只要有部分不符合,則為 false

every看似不常被使用到,實際上在開發時其實 every 可以用來做後端的表單驗證。比方說註冊時前端會傳來幾個欄位:user、password、gender、name、email,假設這些資料存在 data 裡面好了。

換句話說,data 含有這五個欄位。

這時就可以用 every 來檢查他們是不是都含有值:

  const requirements = ['user', 'password', 'gender', 'name', 'email'];
  if (requirements.every(x => array[x] !== undefined)) {
    console.log('必要的欄位都不是空值');
    // 必要的欄位都不是空值
  } else {
    console.log('有些必要的欄位是空值');

    // 有些必要的欄位是空值
  }

some

some() 與 every() 非常接近,都是回傳 true or false,差異僅在 every() 需完全符合,some() 僅需要部分符合。接受一個 callback 函式,callback 可以有三個參數(item, index, array),

  • element:陣列元素的值。
  • index:陣列元素的所在位置。
  • arr:陣列
var ans = people.some(function(item, index, array){
  return item.age > 10 // 當全部 age 大於 10 才能回傳 true
});
console.log(ans);  // true: 只要有部分符合,則為 true

同樣 some 也可以用來這樣檢查。假設 facebook、twitter、github 的社群帳號他一定要有留至少一個,不能都不填的話,就可以這樣做:

const socialAccounts = ['facebook', 'twitter', 'github'];
if (socialAccounts.some(x => data[x] !== undefined)) {
    // 至少有填寫一個社群帳號
} else {
    // 完全沒有填寫社群帳號
}

find

find() 與 filter() 很像,但 find() 只會回傳一次值,且是第一次為 true 的值。接受一個 callback 函式,callback 可以有三個參數(item, index, array),

  • element:陣列元素的值。
  • index:陣列元素的所在位置。
  • arr:陣列
var findAgeThan5 = people.find(function(item, index, array){
  return item.age > 5;           // 取得大於五歲的
});

reduce

educe() 和其他幾個差異就很大了,他可以與前一個回傳的值再次作運算。常常拿來應用於陣列中每個元素的「累加」或是「比較」
接受一個 callback 函式,callback 可以有三個參數(accumulator, currentValue, currentIndex, array), initialValue)

  • accumulator:經由個別 currentValue 加總的累計值
  • currentValue:Array 的個別 item
  • currentIndex:Array item 的索引
  • array:呼叫該 Array method 的陣列
  • initialValue:第一次呼叫時要傳入的累加器初始值。(選擇性 )若沒有提供初始值,則原陣列的第一個元素將會被當作初始的累加器。
const arr = [1, 2, 3, 4, 5];
const reduceArr = arr.reduce((accumulator, currentValue) => {
  console.log(accumulator); // 0, 1, 3, 6, 10
  console.log(currentValue); // 1, 2, 3, 4, 5
  return accumulator + currentValue
}, 0);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值