왜 이걸 알아야할까?
- 많은 데이터들 속에서 내가 원하는 부분만 사용 및 가공하기 위해서?
다양한 방법들
1. 반복문 사용하기
- for 문
const example = [1, 2 , 3, "a", "김"]
const target = "김"
// for반복문 사용
function findTarget(array){
for (let i=0; i < array.length; i++){
if(array[i] === target){
return i;
}
}
}
const result = findTarget(example)
console.log(result, example[4]) // 4, "김"
// 값이 여러개 일 때 모두 찾기
// 새로운 배열을 만들어서 담는다, index든 값이든 선택
const example = [1, "김" ,2 , 3, "a", "김", "김"]
const target = "김"
// for반복문 사용
function findTarget(array){
const result = [];
for (let i=0; i < array.length; i++){
if(array[i] === target){
result.push(i);
}
}
return result;
}
const result = findTarget(example)
console.log(result) // [1,5,6]
- while 문
// while문 사용
const examples = [1, 2 , 3, "a", "ㅊ", "c", "우마왕", "드래곤볼"]
const 드래곤볼 = "드래곤볼"
function 찾아라드래곤볼(array){
let i = 0
while(i < array.length){
if(array[i] === 드래곤볼){
return i;
}
i++ // 반복문에서 i 변수를 증가시켜야한다.
}
return -1; // 못찾았을 경우 -1을 반환한다.
}
const 찾았다드래곤볼 = 찾아라드래곤볼(examples)
console.log(찾았다드래곤볼, examples[찾았다드래곤볼]) // 7, 드래곤볼
// 값이 여러개일 경우 모두 찾기
const examples = [1, 2 , 3,"드래곤볼", "드래곤볼", "a", "ㅊ", "c", "우마왕", "드래곤볼"]
const 드래곤볼 = "드래곤볼"
function 찾아라드래곤볼(array){
let i = 0
let newArr = []
while(i < array.length){
if(array[i] === 드래곤볼){
newArr.push(i)
}
i++ // 반복문에서 i 변수를 증가시켜야한다.
}
return newArr;
}
const 찾았다드래곤볼 = 찾아라드래곤볼(examples)
console.log(찾았다드래곤볼) // [3,4,9]
2. indexOf() 메서드
const example = [1, 2 , 3, "a", "김"]
const target = "김"
const index = example.indexOf(target)
console.log(index) // 4, 찾으면 해당 요소의 인덱스를 반환, 없으면 -1을 반환
3. find() 메서드
const example = [1, 2 , 3, "a", "김"]
const target = "김"
const index = example.find(ele => ele === target)
console.log(index) // "김", 찾으면 해당 요소를 반환, 없으면 undefined을 반환
4. filter() 메서드
const example = [1, 2 , 3, "김", "김", "a", "김"]
const target = "김"
const index = example.filter(ele => ele === target )
console.log(index) // ["김", "김", "김"]
5. includes() 메서드
const example = [1, 2 , 3, "김", "김", "a", "김"]
const target = "김"
const index = example.includes(target)
console.log(index) // true
6. forEach() 메서드
const example = [1, 2 , 3, "김"]
const target = "김"
function findTarget(array){
let index = -1;
array.forEach((element, i) => {
if(element === "김"){
index = i;
}
});
return index;
}
const result = findTarget(example);
console.log(result); // 3
7. map() 메서드
const example = [1, 2 , 3, "김"]
const target = "김"
function findTarget(array){
let targetIndex = -1;
example.map((ele, index) => {
if(ele === target){
targetIndex = index;
}
})
return targetIndex;
}
const result = findTarget(example);
console.log(result); // 3, 배열 내 target이 여러개일 경우 가장 마지막 target요소의 index를 반환한다.
'개발공부 > Javascript' 카테고리의 다른 글
#기본기9_Promise (0) | 2024.04.03 |
---|---|
#기본기8_객체에서 속성을 추가하거나 삭제하는 방법 (0) | 2024.04.03 |
#기본기6_문자열 내에서 변수 사용하기 (0) | 2024.04.02 |
#기본기5_비교연산자 (==와 ===, null과 undefined) (0) | 2024.04.02 |
#기본기4_문자열과 숫자의 결합 (0) | 2024.04.02 |