【问题标题】:parameter connection problem. How can I deal with this参数连接问题。我该如何处理
【发布时间】:2020-01-31 12:56:37
【问题描述】:

不幸的是,我的理解混乱了。

function sendRequest(data: string, cb: (response: any) => void) {
  return cb({ data: "Hi there!" });
}

sendRequest("Send this!", response => {
  console.log(response);
  return true;
}

我认为结果是 {“发送这个!” : “你好呀!} 但答案是 {data : "Hi there!"}

什么参数“data”不能连接到对象内部的数据? 如果我想要这个结果,我应该改变什么?

【问题讨论】:

    标签: javascript typescript parameters callback


    【解决方案1】:

    此行为是由于您的对象将 data 理解为键的名称,而不是尝试获取变量的内容。您需要输入[data],以便它解析为变量内的字符串。 你可以这样做:return cb({ [data]: "Hi there!" });

    【讨论】:

    • 真的很清楚!和简洁。感谢您的帮助。
    • 很高兴能帮上忙。不要忘记将帮助您的答案添加为正确答案,以便遇到相同问题的人可以找到相同的解决方案。 =)
    • 对不起,我是 stackoverflow 的新手。我点了勾。你要求我这样做对吗?
    • @AndersonKim 是的! =)
    【解决方案2】:

    如果你想这样做,你可以这样做:

    function sendRequest(data: string, cb: (response: any) => void) {
      let result = {};
      result[data] = "Hi there!";
      return cb(result);
    }
    
    sendRequest("Send this!", response => {
      console.log(response);
      return true;
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-28
      • 2013-03-14
      • 1970-01-01
      • 1970-01-01
      • 2011-07-21
      • 1970-01-01
      • 2016-08-31
      • 1970-01-01
      相关资源
      最近更新 更多