2014-02-15 2 views
2

forEach()에 의해 생성 된 객체 배열과 newData를 어떻게 구합니까? 전 세계적으로 var result = []을 정의하고 console.log(result);array.protoype.foreEach()의 결과를 정의되지 않은 변수에 저장

var paragraphs = ["this is a p", "%%this is an h2", "%this is an h1"]; 

var newData = paragraphs.forEach(function(x) { 
    var result = []; 
    var header = 0; 
    while (x.charAt(header) === "%") 
    header++; 

    if (header > 0) { 
     result.push({type:"h" + header, content: x.slice(header)}); 
    } else { 
     result.push({type: "p", content: x}); 
    } 
     return result; 

}); 

console.log(newData); // undefined 
+2

forEach는 for 루프와 같습니다. 당신은'map'을 원합니다. – Blender

+0

Thx -지도에 익숙합니다. - 죄송합니다. - 나는주의해야합니다. 그러나이 경우 값을 반환 할 수없는 이유를 이해하려고 노력하고 있습니다. 그것의 다만 저를 도청하는 - 또는 나는 다만 그것을 떨어 뜨려야한다. – jamie

+0

여기를보세요 : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach –

답변

1

forEach 그냥 배열을 통해 루프 경우 작동 - 그것은 새로운 배열을 만들지 않습니다. JavaScript의 Array 프로토 타입에 대한 맵 함수는 배열을 반복하며 콜백 함수에서 제공하는 논리를 수행하지만 콜백이 주어진 경우 새 배열을 반환합니다. 지도 기능에 대한 자세한 내용은 MDN : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

0

안녕하세요. @jamie이 작업에는 map()을 사용해야합니다.

forEach()을 사용하려는 경우 Immediately-Invoked Function Expression을 시도하십시오. 일반적으로 클로저를 사용하여 개인 메서드를 에뮬레이트하는 데 사용됩니다.

는 여기에 대한 jsfiddle의이 코드

var paragraphs = ["this is a p", "%%this is an h2", "%this is an h1"]; 

/* Using Immediately-Invoked Function Expression */ 
var newData = (function() { 
    var result = [] 
    paragraphs.forEach(function (x) { 
     var header = 0; 
     while (x.charAt(header) === "%") 
      header++; 

     if (header > 0) { 
      result.push({type: "h" + header, content: x.slice(header)}); 
     } else { 
      result.push({type: "p", content: x}); 
     } 
    }); 
    return result; 
})(); 

console.log(newData); 

/* Using Map */ 

var newestData = paragraphs.map(function (x) { 
    var header = 0; 
    while (x.charAt(header) === "%") 
     header++; 

    if (header > 0) { 
     x = {type: "h" + header, content: x.slice(header)}; 
    } else { 
     x = {type: "p", content: x}; 
    } 
    return x; 
}); 

console.log(newestData); 

에서 보라.

관련 문제