如何进行以下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];