问题:我正在尝试创建一个名为Wizard的构造函数,该函数需要2个参数:name和spells,然后创建一个Wizard对象:
“向导的每个特定实例都必须具有name属性(字符串),spells属性(是字符串数组)和castSpell方法,该方法能够以字符串格式返回随机咒语。”
该对象具有以下属性:名称为“ Gorrok”(字符串),拼写为“ abracadabra”和“ cadabraabra”(数组)。
目标:调用castSpell方法以显示如下所示的随机咒语:Gorrok:abracadabra
代码:到目前为止,我只编写了以下代码,目前还停留在这里!
function Wizard(name, spells){
this.name = name;
this.spells = [spells];
this.castSpell = function(){
var v = Math.random();
if (v >= 1)
document.write(this.name + " : " + this.spells[0]);
else
document.write(this.name + " : " + this.spells[1]);
}
}
var w = new Wizard("Gorrok", "abracadabra", "cadabraabra");
w.castSpell();
因此,Math.random()
将返回0到1之间的数字,因此它永远不会大于1。
另外,您无法将剩余的参数以自己的方式转换为数组。
最简单的解决方法:
function Wizard(name, spells){
this.name = name;
this.spells = spells; // assume spells is already an array
this.castSpell = function(){
var v = Math.random();
if (v >= 0.5)
document.write(this.name + " : " + this.spells[0]);
else
document.write(this.name + " : " + this.spells[1]);
}
}
var w = new Wizard("Gorrok", ["abracadabra", "cadabraabra"]);
w.castSpell();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句