React-Native/javaScript
[JS] for of index 추출하기
TrueSik
2022. 7. 9. 21:17
for(const v of ['a','b','c']) {
console.log(v) // 출력 a b c
}
for of 문을 사용할 때 index 값이 필요를 할 때가 있는데
위의 루프에서는 제공 되지 않습니다.
하지만 ES6에 도입된 entries() 메서드를 사용하여 index를 사용할 수 있다.
for(const [i,v] of ['a','b','c'].entries() ){
console.log(i,v) // 출력 0,a 1,b 2,c
}
참고
https://flaviocopes.com/how-to-get-index-in-for-of-loop/
How to get the index of an iteration in a for-of loop in JavaScript
A for-of loop, introduced in ES6, is a great way to iterate over an array: for (const v of ['a', 'b', 'c']) { console.log(v) } How can you get the index of an iteration? The loop does not offer any syntax to do this, but you can combine the destructuring s
flaviocopes.com