尝试使用对象属性中的值填充字符串 - 获得"未定义"



我正在尝试在CodeWars上求解以下JavaScript Kata,但要获得"未定义"。可以让某人向我展示有关"未定义"的目光。我正在努力理解下面我的代码缺少的内容。干杯。

链接到挑战:https://www.codewars.com/kata/training-js-number-5-basic-data-types-object

我已经通过FreecodeCamp JS OOP和基本教程/课程搜索,以发现类似的问题。通过stackoverflow,reddit搜索,并搜索了许多网站,以获得类似的挑战。下面的代码:

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

尝试以下:

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.";
}

1(基于'指令'

给您一个功能动物,接受1个参数obj这样:{名称:"狗",腿:4,颜色:"白色"},然后返回这样的字符串:"这只白狗有4条腿。"

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();
  function animal(obj){
     return `This ${obj.color} ${obj.name} has ${obj.legs} legs.` 
  }

您可以尝试此

function animal(obj){
  var a={name:"dog",legs:4,color:"white"}
  return "This" + " " + a.color + " " +a.name + " " + "has" + " " + a.legs + " " + "legs.";
}

最新更新