원하는 요소 배열에서 모두 찾기

1
2
3
4
5
6
7
8
9
10
11
var indices = [];
var array = ['hi', 'b', 'hi', 'c', 'hi'];
var element = 'hi';
var idx = array.indexOf(element);

for(;idx !== -1;){
indices.push(idx);
idx = array.indexOf(element, idx + 1);
}

console.log(indices);//[0, 2, 4];

arr.indexOf(searchElement, fromIndex) fromIndex부분은 fromIndex 부분부터 searchElement를 찾으라는 뜻이다. fromIndex가 음수라면, 배열의 처음부터 searchElement를 찾게 되고, fromIndex가 배열의 길이보다 크거나 같다면, -1이 반환된다.

<출처>

배열 특정 요소 삭제

코딩문제를 풀때, 특정 요소를 삭제하는 방법은 자주 사용된다. 아래는 배열의 특정 요소 삭제 방법과 내가 자주 실수하는 포인트들을 정리하였다. 다음은 배열의 특정 요소 삭제 방법 이다.

1
배열이름.splice(인덱스, 1);

간단한 사용 예시

1
2
3
4
var array = [1, 2, "ipad", 3, 4, 5];
var apple = array.splice(2, 1);
//array = [1, 2, 3, 4, 5]
//apple = ['ipad'], apple은 배열, array 타입이 된다

실수하는 포인트

주의사항

  1. slice가 아닌 splice
  2. 문자열에서는 사용이 불가능하다
  3. splice는 기존 배열또한 변형이 일어나며, slice는 기존배열에 변화를 주지 않는다 (2019.5.2 update)

참고 Object의 속성을 지우는 메서드는 delete이다

1
2
3
var object = { Brand: "Samsung", ModelNumber: "2098d0dkd0" };
delete object.ModelNumber; //delete_객체명.속성명
//object = {Brand: 'Samsung'}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×