Js - splice, slice 차이

SUNTUDY·2023년 12월 18일

회원가입 폼 제작 중, 문자 첫 글자만 대문자로 바꾸고 싶었다.
splice를 사용했지만 되지 않았고, 비슷하다는 slice는 아주 잘되는 아이러니한 상황에 직면했다. 그리고 이 간단한 걸 장정 4시간 반만에 이해한 내 머리에게 치얼스다.

고민하게 만든 코드

const getFieldName = (input) => {
  return input.id.slice(0, 1).toUpperCase() + input.id.substring(1);
};

// 여기서 input.id는 'Password2', 'Email' 같은 문자열임.

아묻따 결론

slice는 문자열, 배열 둘 다 사용 가능한 메서드였고, splice는 배열만 사용 가능한 메서드이다.

고로 해당 코드는 문자열을 바꾸는 거였기에 splice가 안 먹는 거였음!!


예시(배열)

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
function qwerty1() {
  return animals.slice(1, 3); 
  // 결과값 :  ['bison', 'camel']
  return animals.splice(1, 3); 
  // 결과값 :  ['bison', 'camel', 'duck']
}

배열에서는 두 메서드에 관한 결과값이 잘 나온다.
(참고 - slice는 end값 결과에 미포함된다. 그래서 'duck' 없음)


예시(문자열)

const animals1 = 'qwertyuasdf';
function qwerty1() {
	return animals1.slice(1, 3); 
 	// 결과값 : we
  	return animals1.splice(1, 3); 
  	//  결과값 : TypeError: animals1.splice is not a function
}

문자열에서는 splice에 에러가 나온다.
(해석 - splice는 함수가 아니다.)


slice 대신 사용할 수 있는 함수

문자열 함수

· String.prototype.substr()
ex) return input.id.slice(0, 1).toUpperCase() + input.id.substr(1);

· String.prototype.substring()
ex) return input.id.slice(0, 1).toUpperCase() + input.id.substring(1);

profile
Boo-yah

0개의 댓글