[JS] array methods, at method, forEach, forEach with maps and sets


コースソース:完全JavaScript Course 2022 Jonas(Udemy)

Simple Array Methods


SLICE


既存のアレイは変更されません.
let arr = ['a', 'b', 'c', 'd', 'e'];

console.log(arr.slice(2)); // ['c', 'd', 'e']
console.log(arr.slice(2, 4)); // ['c', 'd']
console.log(arr.slice(-2)); //['d', 'e']
console.log(arr.slice(1, -2)); //['b', 'c']
console.log(arr.slice()); //['a', 'b', 'c', 'd', 'e']
console.log([...arr]); //['a', 'b', 'c', 'd', 'e']
arrayの浅いコピーのために、以上の2つの方法が可能です!

SPLICE


既存の配列を変更します.既存の配列からアイテムを削除できます.
console.log(arr.splice(2)); //(['c', 'd', 'e']
console.log(arr); //['a','b']

arr.splice(-1);
console.log(arr); //['a', 'b', 'c', 'd']
arr.splice(1, 2);
console.log(arr); //['a','d']

REVERSE


既存のarrayも変わります.
arr = ['a', 'b', 'c', 'd', 'e'];
const arr2 = ['j', 'i', 'h', 'g', 'f'];
console.log(arr2.reverse()); //['f', 'g', 'h', 'i', 'j']
console.log(arr2); // ['f', 'g', 'h', 'i', 'j']

CONCAT


既存の配列は変更されません.
const letters = arr.concat(arr2);
console.log(letters); //['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
console.log([...arr, ...arr2]); //['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

JOIN

console.log(letters.join('-')); //a-b-c-d-e-f-g-h-i-j

Summary


既存の配列を置き換えない:slice、concat、join
既存の配列の置換:splice(配列をspliceとreverseに変更)

The new at Method

const arr = [23, 11, 64];
console.log(arr[0]); //23
console.log(arr.at(0)); //23

//getting last array element
console.log(arr[arr.length - 1]); //64
console.log(arr.slice(-1)[0]); // 64
console.log(arr.at(-1)); //64

//at Methods also works in strings
console.log('jonas'.at(0)); //j
console.log('jonas'.at(-1)); //s

Looping Arrays : forEach

const movements = [200, 450, -400, 3000, -650, -130, 70, 1300];

//for (const movement of movements) {
for (const [i, movement] of movements.entries()) {
  if (movement > 0) {
    console.log(`Movement ${i + 1}: You deposited ${movement}`);
  } else {
    console.log(`Movement ${i + 1}: You withdraw ${Math.abs(movement)}`);
  }
}
//참고 Math.abs(number) => - sign을 없애줌! -1 => 1

console.log('----FOREACH----');
movements.forEach(function (mov, i, arr) {
  if (mov > 0) {
    console.log(`Movement ${i + 1}: You deposited ${mov}`);
  } else {
    console.log(`Movement ${i + 1}: You withdraw ${Math.abs(mov)}`);
  }
});

Summary

  • for(index,item)/forEach(item,index,arr)パラメータ値の順序を覚えてください.
  • for ofとforeachの違い:foreach内ではcontinueとbreakは使用できません.forEach will always loop over the entire array. loopを中断する必要がある場合はfor ofと書きます.
  • forEach With Maps and Sets


    Map

    const currencies = new Map([
      ['USD', 'United States dollar'],
      ['EUR', 'Euro'],
      ['GBP', 'Pound sterling'],
    ]);
    
    currencies.forEach(function (value, key, map) {
      console.log(`${key}: ${value}`);
    });
    // USD: United States dollar
    // EUR: Euro
    // GBP: Pound sterling

    Set

    const currenciesUnique = new Set(['USD', 'GBP', 'USD', 'EUR', 'EUR']);
    console.log(currenciesUnique); //Set(3) {'USD', 'GBP', 'EUR'}
    currenciesUnique.forEach(function (value, _, map) {
      console.log(`${value}: ${value}`);
    });
    //set에는 key가 존재하지 않으므로! key를 _라고 적음. _ : unneccesary
    //USD: USD
    //GBP: GBP
    //USD: USD