TIL. javascript Array 객체 forEach(), indexof()

Devback·2020년 8월 2일
0

Array foreach()

구문
ele.forEach(function ( item, array, array){}

const fruits = ['apple', 'banana', 'melon', 'orange', 'apple'];
for(let i = 0; i < fruits.length; i++){
  console.log(fruits[i]);
}
const fruits = ['apple', 'banana', 'melon', 'orange', 'apple'];
```jsx
for(let fruit of fruits){
  console.log(fruit);
}
const fruits = ['apple', 'banana', 'melon', 'orange', 'apple'];

fruits.forEach( fruit => {
  console.log(fruit);
})

forEach는 for문과 for in 구문보다 보다 쉽게 배열을 호출할 수 있다.

Array indexof()

구문
arr.indexOf(searchElement[, fromIndex])

searchElement : 배열에서 찾을 요소
fromIndex : 검색을 시작할 색인.

배열 내의 요소의 최초의 인덱스. 발견되지 않으면 -1이 출력된다.

const fruits = ['apple', 'banana', 'orange', 'melon'];

let fruit = fruits.indexOf('apple');
console.log(fruit);
// 0
var array = [2, 9, 9];
array.indexOf(2);     // 0
array.indexOf(7);     // -1
array.indexOf(9, 2);  // 2
array.indexOf(2, -1); // -1
array.indexOf(2, -3); // 0
profile
나랑 같이 개발할 사람🖐

0개의 댓글