JavaScript 单引号不可行?

huangapple go评论80阅读模式
英文:

JavaScript Single Strings Not Possible?

问题

I'm trying to have something like this:

let temp = {`${otherName}`: `${otherValue}`}

but I get a lot of errors with it.

I expected no errors, and I know it's a typo, but I've searched for a solution for 1 hour. I tried different quotes.

Code:

const otherName = document.getElementById('adminPanelManageUserOtherName').value;
const otherValue = document.getElementById('adminPanelManageUserOtherValue').value;

let temp = {`${otherName}`: `${otherValue}`}
英文:

Im trying to have something liek this:

let temp={`${otherName}`: `${otherValue}`}

but I get alot of errors with it.

I expected no errors and I know its a typo but ive searched for a soulision for 1 hour. I tried different quotes.

code:

 const otherName = document.getElementById(`adminPanelManageUserOtherName`).value;
    const otherValue = document.getElementById(`adminPanelManageUserOtherValue`).value;

let temp={`${otherName}`: `${otherValue}`}

答案1

得分: 2

有多种实现你想要的方法。最基本的实现方式是使用 computed property key

let temp = { [otherName]: otherValue };

方括号语法允许你根据放在内部的变量动态生成一个键。

如果出于某些原因你需要在对象中动态添加多个值(因为根据你的操作,你从元素中获取值),那么你可能可以使用以下方式:

let temp = {};
// 循环或其他操作
temp[otherName] = otherValue;

这对于循环或添加多个键值对非常有用。

英文:

there are multiple ways to implement what you want. The most basic implementation is by using computed property key

let temp = { [otherName]: otherValue };

the square brackets syntax allows you to dynamically make a key based on the variable you put inside.

If for some reasons you need to dynamically add multiple values in an object (since from what you're doing you're getting values from an element), then you can probably use this:

let temp = {};
// loop or something
temp[otherName] = otherValue;

this is useful for loops or adding multiple key-value pairs.

答案2

得分: 0

你可以首先创建 temp,然后使用模板字符串将值分配给它:

let temp = {};
temp[`${otherName}`] = `${otherVale}`;
英文:

You could create temp first and then use template strings to assign values to it:

let temp = {};
temp[`${otherName}`] = `${otherVale}`;

huangapple
  • 本文由 发表于 2023年5月31日 23:18:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76375042.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定