开发者

What's wrong in my JavaScript code?

I can't figure out what's wrong.

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


for (var i = 0; i < ferrari.length; i++) {

ferrari is not an Array, but you are trying to access it like it is. Remove this and its corresponding end brace.

You also should change output[i] = ...; to output.push(...); or output[output.length] = ...;, which would eliminate the need to increment i manually.


for (var i in ferrari) output.push(ferrari[i]);

It'd be a little more robust to do:

for (var i in ferrari)
  if (ferrari.hasOwnProperty(i))
    output.push(ferrari[i]);


From what i'm seeing, your for...in is looping over the same object that the outer for is. This will set every item of output to the last key of ferrari, if ferrari has a length -- or give you errors about undefined properties if it doesn't.

What you probably wanted to do instead:

for (var a in ferrari) {
    output[output.length] = a; // or ferrari[a] if you wanted values, not keys
}

and get rid of the outer for loop entirely.


Do you mean

i = 0;
for (var a in ferrari) {
    output[i++] = a;
}

? ferrari does not have length property.


ferrai is an Object and it doesn't have a property by name length (an array does). Change your code to as below:

<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>


why not just override the toString() for the object?

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;
  };
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜