2017-12-11 5 views
0

나는 .reduce()으로 실험 중이며 아래의 테스트 코드에서 accumulator.key[index]의 값을 1로 설정하려고 시도합니다. console.log을 사용하면 해당 인덱스가 0에서 3까지 순환되고 있음을 알 수 있습니다. 그러나 내 코드는 accumulator.key[3] 만 값으로 설정합니다 1. 첫 번째 3 accumulator.key[index]은 정의되지 않은 상태로 둡니다. 이것은 나에게 완전히 당혹 스럽다. 왜 4 키를 모두 1로 설정하지 않았는지 알 수 없습니다. 어떤 도움을 주셔서 감사합니다! 왜 reduce() 메서드에서 인덱스가 예기치 않게 작동합니까?

+2

accumulator.key '= []'의 모든 단계에 .reduce '()' – Andreas

답변

2

"use strict"; 
 

 
var testArray = ['fe', 'fi', 'fo', 'fum']; 
 
var output; 
 
\t 
 
output = testArray.reduce((accumulator, currentValue, index) => { 
 
    accumulator.key = []; 
 
    console.log(index); 
 
    accumulator.key[index] = 1; 
 
    return accumulator; 
 
}, []); 
 

 
console.log(output.key);

당신이 문 accumulator.key = []에 모든 반복에 이전 배열 참조를 제거 key 특성 새로운 []에 할당합니다. 배열 대신 객체를 전달하고 배열에 key 속성을 정의하십시오.

var testArray = ['fe', 'fi', 'fo', 'fum']; 
 
var output; 
 
\t 
 
output = testArray.reduce((accumulator, currentValue, index) => { 
 
    console.log(index); 
 
    accumulator.key[index] = 1; 
 
    return accumulator; 
 
}, { key: [] }); 
 

 
console.log(output.key);

+0

절대적 정확! 나는 각 사이클을 리셋하고 있음을 간과했다. 고맙습니다! – DR01D

1

나는 배열에 .key를 사용하는 사용 사례에 대해 확실하지 오전하지만 당신이 다음 결정 어떤 경우 단지 각각의 반복에 배열로 초기화하지 않습니다. 그리고 첫 번째 반복에서 정의되지 않은 것을 얻는 것을 두려워하면 대체 배열을 사용하십시오.

accumulator.key = (accumulator.key || []); 

"use strict"; 
 

 
var testArray = ['fe', 'fi', 'fo', 'fum']; 
 
var output; 
 
\t 
 
output = testArray.reduce((accumulator, currentValue, index) => { 
 
    accumulator.key = (accumulator.key || []); 
 
    console.log(index); 
 
    accumulator.key[index] = 1; 
 
    return accumulator; 
 
}, []); 
 

 
console.log(output.key);

+1

나는 대체로 생각하지 않았다. 훌륭한! – DR01D

관련 문제