2014-12-06 54 views
0

我需要为对象的颜色属性赋予一个随机值的对象编写构造函数。这是我写的在JavaScript构造函数中使用函数

var Ghost = function() { 
    // your code goes here 
    var num = Math.floor(Math.rand()*4); 
    if(num === 0){ 
    this.color = "white"; 
    } 
    else if(num === 1){ 
    this.color = "yellow"; 
    } 
    else if(num === 2){ 
    this.color = "purple"; 
    } 
    else if(num === 3){ 
    this.color = "red"; 
    } 
}; 

我从测试套件,错误信息代码战争

TypeError: Object #<Object> has no method 'rand' 
    at new Ghost 
     at Test.describe 

不允许我使用一个构造函数中或功能有一些关于测试套件我不明白?

+3

你的意思'的Math.random()'?没有'Math.rand()'函数。 – ntalbs 2014-12-06 04:12:36

回答

3

该函数的名称是Math.random而不是​​。

要解释错误消息:

TypeError: Object #<Object> has no method 'rand' 

首先尝试找到与“兰特”方法,你试图调用对象。在这种情况下,它是数学。然后验证所讨论的对象的确有方法。


在一个不相关的音符,你的选择的代码可以简化为:

var COLOURS = ['white', 'yellow', 'purple', 'red']; 
this.color = COLOURS[Math.floor(Math.random() * 4)]; 
+1

甚至更​​好将'4'更改为'COLOURS.length'。 – jfriend00 2014-12-06 04:18:27