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

标签 javascript object variables input

我需要一段特定代码的帮助。这有点难以描述,但我会尽力做到最好。我需要根据用户输入检查对象的特定属性。例如,如果用户输入“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/

相关文章:

javascript - HighCharts datetime xAxis 没有缺失值(周末)

javascript - Javascript 中对象创建的异常行为

JAVASCRIPT:如何浏览对象

php - 在 JavaScript 警报/确认框中发送 PHP 变量

ruby - 使用名称访问实例变量(作为符号)

swift - SpriteKit SKSprite节点

javascript - jQuery 动态表输入

javascript - 将 Accordion 中的一项限制为未折叠

javascript - 尝试创建自动点击脚本

单独文件中的 Javascript 对象属性