在JavaScript中将对象传递到数组中
我试图用JavaScript将动态创建的对象传递到数组中。对象通过了,但当我试图检索对象内部的数据时,它消失了。控制台日志 圆形[物体,物体]。我怎样才能做到这一点 这是我的密码:在JavaScript中将对象传递到数组中,javascript,Javascript,我试图用JavaScript将动态创建的对象传递到数组中。对象通过了,但当我试图检索对象内部的数据时,它消失了。控制台日志 圆形[物体,物体]。我怎样才能做到这一点 这是我的密码: function roundList(myRounds){ var savedRounds = []; savedRounds.push(myRounds); console.log("this is savedRounds " + savedRounds); }; function round(course,t
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);
}
不清楚您试图访问对象的位置,但是
var savedRounds=[]中的var
表示SavedLonds仅在本地范围内,并且只能在roundList
方法中访问
如果要在roundList方法之外访问savedronds,请声明savedronds=[]
在roundList
方法之外,或者从该方法返回它,以便其他人可以访问它。改用console.log(JSON.stringify(savedronds))
这将向您显示对象的全部内容
正如其他人所指出的,您现在也没有持久化对象,并且在函数完成后将无法访问它。。。。这意味着当“roundList”返回时,数组就消失了。在Chrome中,你也可以使用
console.log(“Lorem Ipsum”,object)
,仍然可以得到一个很好的可扩展日志条目。只要你使用comas,而不是把所有的东西浓缩成一个字符串。