gpt4 book ai didi

javascript - 如何让用户输入变量名?

转载 作者:行者123 更新时间:2023-12-02 23:15:26 25 4
gpt4 key购买 nike

我需要一段特定代码的帮助。这有点难以描述,但我会尽力做到最好。我需要根据用户输入检查对象的特定属性。例如,如果用户输入“London”,我希望能够访问名为“xcoor.london”的属性。

例如,在我尝试过很多“if”和“else if”之前,

xcoordinate = xcoor.london;
ycoordinate = ycoor.london;
}else if(input == 'Paris'){
xcoordinate = xcoor.paris;
ycoordinate = ycoor.paris;
}else if(input == 'Washington D.C.'){
xcoordinate = xcoor.washdc;
ycoordinate = ycoor.washdc;
}
"But I have dozens of inputs and this takes a lot of code.
I am just revising this program to make it take up less space,
and this part is the major problem.
I want something like this:"
var xcoor = {
london: 0.1278,
paris: 2.3522,
...
}
var input = document.getElementById('input').value;
xcoordinate = xcoor.input;

这就是全部;欢迎并赞赏任何想法!提前致谢!

最佳答案

我会为坐标制作一本字典。像这样:

const coordinates = {
"London": {x: ..., y: ...},
"Paris": {x: ..., y: ...}
};

console.log('The coordinates for London: ',coordinates['London']);
console.log('The x coordinate for Paris: ', coordinates['Paris'].x);

如果你想使用你的input变量来查找坐标,你可以这样做:

const result = coordinates[input];
console.log(result.x, result.y) //returns the x and y coordinates for the user input

关于javascript - 如何让用户输入变量名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57182855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com