【问题标题】:How to run method from string that shares object name如何从共享对象名称的字符串运行方法
【发布时间】:2020-06-14 02:08:41
【问题描述】:

所以我有一个我想在用户输入中检测的对象列表,然后对提到的这些对象执行方法。 我的问题是我可以推断出等于 object.name 属性的字符串,但我找不到一种方法来获取该字符串并将其转换为对象本身。

// My constructor is "Interactable"

input.value = "Feed horse";

var o = "horse" //string achieved through other function in my program identifying the object of a sentence

function shouldIFeedIt() {
     for(l = 0; l < Interactable.length; l++) { //Interactable.length searches through every Interactable until it finds the one named "horse"
          if(Interactable[l] == o) {
               console.log(o); //This logs horse, but I can't turn this into the object upon which I want to run .feed()
               o.feed(); // horse.feed() prints text to the screen, but this does not...
          }
     }

所以 object.isight();是我最终要执行的方法,但我不知道如何从 Interactable[l] 中获取该特定单元。

有什么建议吗?

【问题讨论】:

  • 请提供minimal reproducible example,以便我们更好地了解您的具体问题。换句话说,一些样本输入和预期结果。我们不知道您的对象是什么样的
  • 已编辑以使代码更易于理解。我希望这会有所帮助,我感谢您的回复
  • 并非如此。如果很明显,您现在应该会有更多的反馈和解决方案

标签: javascript arrays for-loop object if-statement


【解决方案1】:

我想这就是你想要的,对吧?

let Interactable = ["cat", "horse"];
let animals = {
  feed: (name) => {
    console.log("Currently feeding: " + name);
  },
};

let o = "horse";

function shouldIFeedIt() {
  for (l = 0; l < Interactable.length; l++) {
    if (Interactable[l] == o) {
      o = { ...animals, name: o };
      o.feed(o.name);
    }
  }
}

shouldIFeedIt();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多