TIL - javascript method

sumin·2022년 5월 26일

every()

  • 콜백 함수가 모든 요소에 대한 true를 반환하면 true
    하나의 요소라도 false가 있다면 false 반환
  • 빈 요소에 대해서는 실행하지 않는다
  • 원래 배열을 변경하지 않는다
const ages = [32, 33, 16, 40];

ages.every(checkAge)

function checkAge(age) {
  return age > 18; // false : 16이 있기 때문이다
}

startwith(), endsWith()

str.startWish(탐색할 문자열 ,[탐색할 위치, 기본값 0])
  • 대상 문자열이 특정 문자 또는 문자열로 시작하는지 확인하여 결과를 true 혹은 false로 반환
  • 공백도 포함이기 때문에 주의 해야 함
var str = 'To be, or not to be, that is the question.';

console.log(str.startsWith('To be'));         // true
console.log(str.startsWith('not to be'));     // false
console.log(str.startsWith('not to be', 10)); // true

map()

  • filter(),forEach()
  • 모든 배열의 값에 함수를 실행하는 메소드이다
  • 배열의 각 요소에 대해 한 번 함수를 호출한다
  • 빈 요소에 대해서는 함수를 실행하지 않는다
  • 원래 배열을 변경하지 않는다
array.map(callbackFunction(currenValue, index, array), thisArg)
  • currentValue : 배열 내 현재 값
  • index : 배열 내 현재 값의 인덱스
  • array : 현재 배열
  • thisArg : callbackFunction 내에서 this로 사용될 값
const numbers = [65, 44, 12, 4];
const newArr = numbers.map(myFunction)

function myFunction(num) {
  return num * 10;
} // [650, 440, 120, 40]
var testJson = [
  { name: "이건", salary: 50000000 },
  { name: "홍길동", salary: 1000000 },
  { name: "임신구", salary: 3000000 },
  { name: "이승룡", salary: 2000000 },
];

var newJson = testJson.map(function (element, index) {
  console.log(element);
  var returnObj = {};
  returnObj[element.name] = element.salary;
  return returnObj;
});
console.log("newObj");
console.log(newJson);

// 결과값
1. console.log(element);
{ name: '이건', salary: 50000000 }
{ name: '홍길동', salary: 1000000 }
{ name: '임신구', salary: 3000000 }
{ name: '이승룡', salary: 2000000 }

2. console.log(newJson);
[{ '이건': 50000000 },{ '홍길동': 1000000 },{ '임신구': 3000000 },{ '이승룡': 2000000 }]

출처 : https://velog.io/@daybreak/Javascript-map
정리를 엄청 잘 해놓으셨다👍

filter()

const ages = [32, 33, 16, 40];
const result = ages.filter(checkAdult);

function checkAdult(age) {
  return age >= 18;
}
// [32, 33, 40]

forEach()

let txt = "";
const fruits = ["apple", "orange", "cherry"];
fruits.forEach(myFunction);

function myFunction(item, index) {
  txt += index + " : " + item + " "; 
} 
console.log(txt)

// 0 : apple 1 : orange 2 : cherry 

slice()

  • slice(begin, end) 시작점 / 끝(포함하지 않음)
  • 배열에서 선택한 요소를 새 배열로 반환
  • 원래 배열을 변경하지 않는다
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]

console.log(animals.slice(-2));
// expected output: Array ["duck", "elephant"]

console.log(animals.slice(2, -1));
// expected output: Array ["camel", "duck"]

console.log(animals.slice());
// expected output: Array ["ant", "bison", "camel", "duck", "elephant"]

0개의 댓글