我正在尝试在Codewars上解决以下Javascript kata,但出现“ undefined”。能否请别人向我展示“未定义”的确切含义。我正在努力了解下面的代码缺少的内容。干杯。
链接到挑战:https://www.codewars.com/kata/training-js-number-5-basic-data-types-object
我已经搜索了FreeCodeCamp JS OOP和Basic教程/课程,以发现类似的问题。通过StackOverflow,Reddit和Google搜索了许多网站以查找类似的挑战。 下面的代码:
function animal(name, legs, color) {
this.name = name;
this.legs = legs;
this.color = color;
}
var dog = new animal("dog", 4, "white");
// similar variables set such for other animal objects.
animal.prototype.toString = function animalToString() {
var sent = "This " + this.color + " " + this.name + " has " + this.legs + " legs.";
return sent;
}
return animal.prototype.toString.call();
预期:This white dog has 4 legs.
,而不是:undefined
答案 0 :(得分:1)
1)基于“说明”
给您一个函数动物,接受1个参数obj,例如:{name:“ dog”,legs:4,color:“ white”},并返回如下字符串:“此白狗有4条腿。” < / p>
function animal({name, legs, color}) {
return `The ${color} ${name} has ${legs} legs.`;
}
2)根据您应该学习的内容
function animal({name, legs, color}) {
this.name = name;
this.legs = legs;
this.color = color;
}
animal.prototype.toString = function animalToString() {
return `The ${this.color} ${this.name} has ${this.legs} legs.`;
}
var dog = new animal({name:"dog", legs:4, color:"white"});
dog.toString();
答案 1 :(得分:0)
尝试一下:
function animal(obj){
var newAnimal = {
name: obj.name,
legs: obj.legs,
color: obj.color
};
return "This " + newAnimal.color + " " + newAnimal.name + " has " + newAnimal.legs + " legs.";
}
我相信本kata的目的是向您介绍javascript对象。更改函数“动物”的输入时会引发此问题。如果查看右下角的样本测试,则输入到您要进行的函数中的输入应仅接受一个参数,该参数是具有属性名称,支路和颜色的对象。您将此输入更改为三个单独的参数,而不只是一个。
或者您可以完全跳过分配,而直接像这样直接访问输入:
function animal(obj){
return "This " + obj.color + " " + obj.name + " has " + obj.legs + " legs.";
}
答案 2 :(得分:-1)
你可以试试这个
function animal(obj){
var a={name:"dog",legs:4,color:"white"}
return "This" + " " + a.color + " " +a.name + " " + "has" + " " + a.legs + " " + "legs.";
}