在JavaScript中将对象传递给数组

时间:2013-09-04 15:21:49

标签: javascript

我正在尝试将动态创建的对象传递到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 个答案:

答案 0 :(得分:2)

目前尚不清楚您尝试访问该对象的位置,但var中的var savedRounds = [];表示savedRounds仅在本地范围内,只能在roundList方法中访问。

如果要在roundList方法之外访问savedRounds,则在savedRounds = [];方法之外声明roundList或从方法返回,以便其他人可以访问它。

答案 1 :(得分:1)

使用console.log(JSON.stringify(savedRounds))代替

这将显示对象的完整内容。

正如其他人所指出的那样,你现在也没有持久化对象,并且在函数完成后将无法访问它。