0

如何进行以下 JS 变量引用:

  1. 当您有一个数组 ( 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];
    }
    
  2. 当您有以下变量列表时:

    var book = "Some Book";
    var shelf = "Some Shelf"
    var bookshelf = "The cake!"
    

在这种情况下,如果我想(无论出于何种原因)引用变量bookshelf,我该如何通过组合其他两个变量的变量名来做到这一点?

我的意思是,我不能这样做,var x = book + shelf;因为那会给我result = "Some BookSome Shelf".

4

2 回答 2

1

不要使它们成为变量,使它们成为对象的属性:

var tags = {
   book: 'Some book',
   shelf: 'Some shelf',
   bookshelf: 'The Cake!'
};

var which = 'bookshelf';
var x = tags[which];
于 2012-04-28T18:56:15.910 回答
1

您可能希望使它们成为对象的属性(尽管它们可能已经是window对象的属性):

var stuff = {
    book: "Some book!",
    shelf: "Some shelf",
    bookshelf: "The cake!"
};

function say(src) {
    // Define the box (some random div element will do)
    var box = document.querySelector('#box');

    box.innerHTML = stuff[response[src]];
}
于 2012-04-28T18:57:41.870 回答