問題描述
參數連接問題。我該如何處理 (parameter connection problem. How can I deal with this)
不幸的是,我的理解混亂了。
function sendRequest(data: string, cb: (response: any) => void) {
return cb({ data: "Hi there!" });
}
sendRequest("Send this!", response => {
console.log(response);
return true;
}
我以為結果是{“發送這個!” : "Hi there!} 但答案是 {data : "Hi there!"}
什麼參數“data”不能連接到對象內部的數據?如果我想要這個結果,我應該改變什麼?
參考解法
方法 1:
If you wanna do that, you could do:
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;
});
方法 2:
This behavior is due to your object understanding data
as the name of the key and is not trying to get the content of the variable. You need to put [data]
so it will resolve to the string inside your variable. You can just do this : return cb({ [data]: "Hi there!" });
(by Anderson Kim、WuDo、Raekh Void)