본문 바로가기
JavaScript/메소드

[javascript] 문자열 밀기 or 민 횟수, unshift(), pop(), indexOf()

by Angry Stock 2023. 8. 27.
반응형
unshift() 메서드는 새로운 요소를 배열의 맨 앞쪽에 추가하고, 새로운 길이를 반환합니다.
const array1 = [1, 2, 3];

console.log(array1.unshift(4, 5));
// Expected output: 5

console.log(array1);
// Expected output: Array [4, 5, 1, 2, 3]
pop() 메서드는 배열에서 마지막 요소를 제거하고 그 요소를 반환합니다.
const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];

console.log(plants.pop());
// Expected output: "tomato"

console.log(plants);
// Expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]

plants.pop();

console.log(plants);
// Expected output: Array ["broccoli", "cauliflower", "cabbage"]
indexOf() 메서드는 배열에서 지정된 요소를 찾을 수 있는 첫 번째 인덱스를 반환하고 존재하지 않으면 -1을 반환합니다.
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// Expected output: 1

// Start from index 2
console.log(beasts.indexOf('bison', 2));
// Expected output: 4

console.log(beasts.indexOf('giraffe'));
// Expected output: -1
연습
function solution1(a, b) {
  return (b + b).indexOf(a);
}

function solution2(a, b) {
  let answer = [];
  let arr = a.split('');
  answer.push(a);
  for (let i = 0; i < a.length - 1; i++) {
    arr.unshift(arr.pop());
    answer.push(arr.join(''));
  }
  return answer.indexOf(b);
}

let a = ['entrophy', 'basement', 'overwhelm', 'kick'];

let b = ['hyentrop', 'mentbase', 'overwhelm', 'ickk'];

for (let i = 0; i < a.length; i++) {
  console.log('solution1', solution1(a[i], b[i]));
  console.log('solution2', solution2(a[i], b[i]));
}
결과

반응형

댓글