我无法弄清楚出了什么问题。
var CarObj = function(passengers, maxLoad, wheels, doors, maxSpeed) {
this.passengers = passengers;
this.maxLoad = maxLoad;
this.wheels = wheels;
this.doors = doors;
this.maxSpeed = maxSpeed;
};
var ferrari = new CarObj(4, "700kg", 4, 2, "360km/h");
var output = new Array();
for (var i = 0; i < ferrari.length; i++) {
for (var a in ferrari) {
output[i] = a;
}
}
document.getElementById('ELEMENTHERE').innerHTML = (output.join(" "));
答案 0 :(得分:2)
for (var i = 0; i < ferrari.length; i++) {
ferrari
不是数组,但您尝试按原样访问它。取下它及其相应的端撑。
您还应将output[i] = ...;
更改为output.push(...);
或output[output.length] = ...;
,这样就无需手动增加i
。
答案 1 :(得分:1)
从我所看到的情况来看,您的for...in
正在循环覆盖外部for
所在的同一个对象。这会将output
的每个项目设置为ferrari
的最后一个键,如果ferrari
有一个长度 - 或者如果没有,则将错误提供给您。
您可能想要做的事情:
for (var a in ferrari) {
output[output.length] = a; // or ferrari[a] if you wanted values, not keys
}
完全摆脱外部for
循环。
答案 2 :(得分:1)
for (var i in ferrari) output.push(ferrari[i]);
这样做会更加健壮:
for (var i in ferrari)
if (ferrari.hasOwnProperty(i))
output.push(ferrari[i]);
答案 3 :(得分:0)
你的意思是
i = 0;
for (var a in ferrari) {
output[i++] = a;
}
? 法拉利没有长度属性。
答案 4 :(得分:0)
ferrai是一个Object,它没有按名称长度的属性(数组有)。 将您的代码更改为:
<script type="text/javascript">
var CarObj = function(passengers, maxLoad, wheels, doors, maxSpeed) {
this.passengers = passengers;
this.maxLoad = maxLoad;
this.wheels = wheels;
this.doors = doors;
this.maxSpeed = maxSpeed;
};
var ferrari = new CarObj(4, "700kg", 4, 2, "360km/h");
var output = new Array();
var i=0;
for (var a in ferrari)
{
output[i] = a;
i++;
}
document.getElementById('ELEMENTHERE').innerHTML = (output.join(" "));
</script>
答案 5 :(得分:0)
为什么不直接覆盖对象的toString()?
var CarObj = function(passengers, maxLoad, wheels, doors, maxSpeed) {
this.passengers = passengers;
this.maxLoad = maxLoad;
this.wheels = wheels;
this.doors = doors;
this.maxSpeed = maxSpeed;
this.toString = function() {
return this.passengers + " " + this.maxLoad + " " + this.wheels + " " + this.doors + " " + this.maxSpeed;
};
};