我知道這個問題已經在這里了,但我不知道如何在我的情況下使用它。
我有一個回傳字串化 JSON 的函式,但我需要使用此函式的引數更改一個鍵。我試過這樣的東西來替換它的值:
function toJSON(... name: string, timestamp: number, x :number, y: number ...): string {
return JSON.stringify({
...
`${name}`: [
{
timestamp: timestamp,
x: x,
y: y
}
]
...
})
有沒有一種簡單的方法可以用引數替換這個鍵?
這...意味著更多的東西之前和之后
uj5u.com熱心網友回復:
幾乎很好,您應該使用計算屬性https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#new_notations_in_ecmascript_2015而不是字串模板:
function toJSON(... name: string, timestamp: number, x:number, y: number ...): string {
return JSON.stringify({
...
[name]: [{ timestamp, x, y }]
});
};
從 es2015 開始,您可以使用簡寫的屬性名稱,因此您可以撰寫{ timestamp, x, y }而不是冗余:{ timestamp: timestamp, x: x, y: y }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/434857.html
