2013-09-04 7 views
2

동적으로 생성 된 객체를 JavaScript의 배열에 전달하려고합니다. 개체가 전달되지만 개체 내부의 데이터를 검색하려고하면 사라집니다. 콘솔에 [object, object]가 기록됩니다. 이 일을 어떻게 할 수 있습니까? 당신이 개체에 액세스하려고하고 있지만 var savedRounds = [];var이 savedRounds는 로컬 범위 및 roundList 방법 내부에서만 액세스 할 의미 어디JavaScript의 배열에 객체 전달

function roundList(myRounds){ 

var savedRounds = []; 
savedRounds.push(myRounds); 
console.log("this is savedRounds " + savedRounds); 
}; 

function round(course,tee,slope,rating,score){ 
this.course=course; 
this.tee=tee; 
this.slope=slope; 
this.rating=rating;   
this.score=score; 
} 

function makeRound(){ 
var newCourse = document.getElementById('course').value 
var newTee = document.getElementById('tee').value 
var newSlope = document.getElementById('slope').value 
var newRating = document.getElementById('rating').value 
var newScore = document.getElementById('score').value 
var newDate = document.getElementById('date').value 
var newRound = new round(newCourse,newTee,newSlope,newRating,newScore); 
    roundList(newRound); 
} 

답변

2

그것은하지 분명하다 :

여기 내 코드입니다.

roundList 메서드 외부에서 savedRounds에 액세스하려면 roundList 메서드 외부에 savedRounds = [];을 선언하거나 다른 메서드에서 반환하여 다른 사람이 액세스 할 수 있도록합니다.

+3

... "roundList"가 반환되면 배열이 사라짐을 의미합니다. – Pointy

1

사용 console.log(JSON.stringify(savedRounds)) 대신 당신에게 객체의 전체 내용을 표시합니다

.

다른 사람들도 지적했듯이 개체를 지금도 유지하지 않고 있으며 함수가 완료된 후에도 액세스 할 수 없습니다.

+1

크롬에서는'console.log ("Lorem Ipsum", object)'를 사용할 수 있으며 멋진 확장 가능한 로그 항목을 얻을 수 있습니다. 모든 것을 문자열로 연결하는 대신에 혼수 상태를 사용하는 한. – zatatatata