Reputation: 17
just a simple question that i really want an answer too because i don't understand it 100 %
Javascript
Example: Say you prompt a user for there name. simple enough right ? But you have an Array stating a few names (one of which is there's) sooo basically what im saying so far:
var names = new Array("bob", "joe", "steve", "sabrina");
You prompt the user for there name, they enter in "bob". But now you only want to display Bob's age which is also located in an array of yours:
var ages = new Array("12","45","32","22");
The names and ages are the same, like in order. so bob is 12, joe 45, etc. now, back to my main question. Since the user enters in "Bob" how would you go about displaying the age "12", or if the user entered "joe" display "45"?
Thank you for your time! (:
p.s. all additional information and facts about this topic are appreciated!
Upvotes: 0
Views: 39
Reputation: 59293
Try
ages[names.indexOf("bob")]; // 12
Note that an object (associative array) would be better for this kind of data. For example:
ages = {
bob: 12,
joe: 45,
// etc.
};
Now you can do this:
ages.bob; // 12
Or:
var name = 'bob';
ages[name]; // 12
from my knowledge, the object "indexOf" doesn't actually work with all browsers, is there an alternate method of outputting the data using the arrays? – Ryanrrjk 49 secs ago
indexOf
works in basically everything except IE8. If you need to support IE8 or lower, you could use a shim, such as:
Array.prototype.indexOf = function(item) {
var i = this.length;
while (i-- > 0) if (this[i] === item) return i;
return -1;
}
Upvotes: 2