我的JavaScript代码有什么问题?

时间:2010-12-30 19:38:41

标签: javascript client-side

我无法弄清楚出了什么问题。

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(" "));

6 个答案:

答案 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;
  };
};