英文:
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}`;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论