How do you make the following JS variable references:
When you have an array ( x[0], x[1], ...
), and you have a button like so:
<button onclick="say(0)"></button>
The function looks like this:
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]; }
When you have the following list of variables:
var book = "Some Book"; var shelf = "Some Shelf" var bookshelf = "The cake!"
In this case, if I want to (for whatever reason) refer to the variable bookshelf
, how do I do it by combining the variable names of the other two variables?
I mean, I can't do var x = book + shelf;
since that will give me the result = "Some BookSome Shelf"
.
Don't make them variables, make them properties of an object:
var tags = {
book: 'Some book',
shelf: 'Some shelf',
bookshelf: 'The Cake!'
};
var which = 'bookshelf';
var x = tags[which];
You'll probably want to make them properties of an object (although they're probably already properties of the window
object):
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]];
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.