我一直得到TypeError:testsession.testset [0] .athletes未定义 - 我尝试了很多不同的方法,是不是有一个对象数组的数组
var testsession = {};
var testsetname = {};
var testset = [];
testsession.testsetname = testsetname;
testsession.testsetname = "week9";
testsession.testset = testset;
testsession.testset.push("400M");
testsession.testset.push("800M");
var athletes = [];
var Time = "49.2";
var AthleteID = "a92";
var athlete = { "AthleteID": AthleteID, "Time": Time};
//console.log(pointer);
testsession.testset[0].athletes = athletes;
testsession.testset[0].athletes.push(athlete)
console.log(testsession.testset[0].athletes[0]);
答案 0 :(得分:1)
当您尝试访问testsession.testset[0]
时,该条目是一个字符串。您可能至少想在访问其成员之前设置testsession.testset[0] = {};
。
答案 1 :(得分:1)
testset [0]是一个字符串。使它成为一个对象
var testsession = {};
var testsetname = {};
var testset = [];
testsession.testsetname = testsetname;
testsession.testsetname = "week9";
testsession.testset = testset;
//Earlier you pushed 400m directly which is a string hence causing the error later on
testsession.testset.push({distance: "400M"});
testsession.testset.push({distance: "800M"});
var athletes = [];
var Time = "49.2";
var AthleteID = "a92";
var athlete = { "AthleteID": AthleteID, "Time": Time};
//console.log(pointer);
testsession.testset[0].athletes = athletes;
testsession.testset[0].athletes.push(athlete)
console.log(testsession.testset[0].athletes[0]);
答案 2 :(得分:1)
testsession.testset[0]
是一个原始值,一个字符串。
因此,以下陈述不会产生您认为的影响:
testsession.testset[0].athletes = athletes;
这里发生了什么?左侧的原语没有athletes
属性,但JavaScript会将其强制转换为String
对象,然后将该属性分配给该临时String
对象,然后该对象消失为遗忘。
所以就像从未发生过赋值一样:testsession.testset[0]
将保持原始值,而原始值没有属性。
当您阅读athletes
属性时,同样会再次发生:JavaScript将其强制转换为String
对象,只发现该对象没有athletes
属性,因此您获得undefined
。
答案 3 :(得分:0)
我认为你正在使用这样的代码。
<script >
var testsession = {};
testsession.testset = [];
testsession.testset.push({testsetname:"week9"});
testsession.testset[0].list = [];
testsession.testset[0].list.push({distance:"400M"});
testsession.testset[0].list[0].athletes = [];
testsession.testset[0].list[0].athletes.push({ AthleteID: "a92", Time: "49.2"});
testsession.testset[0].list.push({distance:"900M"});
testsession.testset[0].list[1].athletes = [];
testsession.testset[0].list[1].athletes.push({ AthleteID: "a93", Time: "99.2"});
console.log(testsession);
</script>
结果将是这样的:
"{"testset":[{"testsetname":"week9","list":[{"distance":"400M","athletes":[{"AthleteID":"a92","Time":"49.2"}]},{"distance":"900M","athletes":[{"AthleteID":"a93","Time":"99.2"}]}]}]}"