How do I create a method for an array class?
Sorry, I know this is Programming 101, but I cannot find good documentation ...
I have an array and I want each member to be as an object and then call them with the assigned name (it would be much easier if javascript allowed values ββother than number). For instance:
var things = ['chair', 'tv', 'bed'];
var costs = ['10', '100', '75'];
for (var i = 0; i < things.length; i++) {
thing.name = things[i];
thing.cost = costs[i];
}
alert(thing.name('tv').cost);
Obviously this is not a way to do it, but the desired result would be a warning that says "100".
I got to the point of creating a class that has a method named name that points to the main object, for example:
function thing(name, cost) {
function name(thename) {
return this;
}
this.thingname = name;
this.name = name;
this.cost = cost;
}
But that still requires each object to have a unique variable name, which goes against the whole point. I want to just throw my entire array into some generic class and call the values ββI want by name.
I know this is probably an easy one to ask here, but I'm stuck!
Thanks.
a source to share
why don't you try JSON:
like
var myArray= {"things": [
{"name":"chair","price":"10"},
{"name":"tv","price":"100"},
{"name":"bed","price":"75"}
]};
//now you can use it like this
for(var i=0; i< myArray.things.length; i++)
{
alert(myArray.things[i].name + " costs " + myArray.things[i].price);
}
a source to share
If you need to do this using the original data format (because you don't influence it) use the following:
var things = ['chair', 'tv', 'bed'];
var costs = ['10', '100', '75'];
var associatedThings;
for(i=0,x=things.length;i<x;i++){
associatedThings[things[i]] = {cost: costs[i]};
}
alert(associatedThings['tv'].cost);
a source to share