如何进行以下 JS 变量引用:
当您有一个数组(
x[0], x[1], ...
),并且您有一个如下所示的按钮时:<button onclick="say(0)"></button>
该函数如下所示:
function say(src){ // Define the box (some random div element will do) var box = document.querySelector('#box'); // This is wrong, I know... I need to refer to the variable 'response[0]' in this case... box.innerHTML = response[src]; }
当您有以下变量列表时:
var book = "Some Book"; var shelf = "Some Shelf" var bookshelf = "The cake!"
在这种情况下,如果我想(无论出于何种原因)引用变量 bookshelf
,我该如何通过组合其他两个变量的变量名来实现?
我的意思是,我不能这样做 var x = book + Shelf;
因为这会给我 result = "Some BookSome Shelf"
。
最佳答案
不要将它们设为变量,而将它们设为对象的属性:
var tags = {
book: 'Some book',
shelf: 'Some shelf',
bookshelf: 'The Cake!'
};
var which = 'bookshelf';
var x = tags[which];
关于javascript - 在 JavaScript 中引用复杂变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10366553/