반응형
inside map() 함수 내 인덱스
인덱스 번호를 취득하는 방법이 없습니다.map
을 사용하여 기능하다List
부터Immutable.js
:
var list2 = list1.map(mapper => { a: mapper.a, b: mapper.index??? }).toList();
문서에는 다음과 같은 내용이 기재되어 있습니다.map()
돌아온다Iterable<number, M>
제가 필요한 우아한 방법이 없을까요?
현재 반복을 얻을 수 있습니다.index
를 위해map
메서드에서 두 번째 매개 변수를 사용합니다.
예:
const list = [ 'h', 'e', 'l', 'l', 'o'];
list.map((currElement, index) => {
console.log("The current iteration is: " + index);
console.log("The current element is: " + currElement);
console.log("\n");
return currElement; //equivalent to list[index]
});
출력:
The current iteration is: 0 <br>The current element is: h
The current iteration is: 1 <br>The current element is: e
The current iteration is: 2 <br>The current element is: l
The current iteration is: 3 <br>The current element is: l
The current iteration is: 4 <br>The current element is: o
다음 항목도 참조하십시오. https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/map
파라미터
callback - 3개의 인수를 사용하여 새로운 배열 요소를 생성하는 함수입니다.
1) 현재 가치
배열에서 처리 중인 현재 요소.2) 인덱스
배열에서 처리 중인 현재 요소의 인덱스입니다.3) 어레이
어레이 맵이 호출되었습니다.
Array.prototype.map()
인덱스:
인덱스에 액세스할 수 있습니다.Array.prototype.map()
콜백 함수의 두 번째 인수를 사용합니다.다음은 예를 제시하겠습니다.
const array = [1, 2, 3, 4];
const map = array.map((x, index) => {
console.log(index);
return x + index;
});
console.log(map);
의 기타 인수Array.prototype.map()
:
- 콜백 함수의 세 번째 인수는 맵이 호출된 배열을 표시합니다.
- 의 두 번째 논거는
Array.map()
이 오브젝트에는this
콜백 함수의 값.화살표 함수에 대한 자체 바인딩이 없기 때문에 콜백을 선언하려면 regular 키워드를 사용해야 합니다.this
키워드를 지정합니다.
예를 들어 다음과 같습니다.
const array = [1, 2, 3, 4];
const thisObj = { prop1: 1 }
const map = array.map((x, index, array) => {
console.log(array);
console.log(this)
}, thisObj);
- 다음과 같은 배열이 있다고 가정합니다.
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
arr.map((myArr, index) => {
console.log(`your index is -> ${index} AND value is ${myArr}`);
})
> output will be
index is -> 0 AND value is 1
index is -> 1 AND value is 2
index is -> 2 AND value is 3
index is -> 3 AND value is 4
index is -> 4 AND value is 5
index is -> 5 AND value is 6
index is -> 6 AND value is 7
index is -> 7 AND value is 8
index is -> 8 AND value is 9
Ramda 사용:
import {addIndex, map} from 'ramda';
const list = [ 'h', 'e', 'l', 'l', 'o'];
const mapIndexed = addIndex(map);
mapIndexed((currElement, index) => {
console.log("The current iteration is: " + index);
console.log("The current element is: " + currElement);
console.log("\n");
return 'X';
}, list);
언급URL : https://stackoverflow.com/questions/38364400/index-inside-map-function
반응형
'source' 카테고리의 다른 글
여러 열에 걸쳐 고유한 sqlalchemy (0) | 2022.12.04 |
---|---|
MariaDB: Count Different는 도청되었습니까? (0) | 2022.11.24 |
NumPy 어레이에서 NaN 값을 삭제하려면 어떻게 해야 합니까? (0) | 2022.11.24 |
Mac용 ext-zip 설치 (0) | 2022.11.24 |
이 쿼리 mysql 및 레일 5를 개선하는 방법 (0) | 2022.11.24 |