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.

0


a source to share


6 answers


Why not use objects?



var things = {
  chair: 10,
  tv: 100,
  bed: 75
};
alert(things.chair); // 10
alert(things['tv']); // 100

      

+5


a source


var stuff = {
    chair: 10,
    tv: 100,
    bed: 75
};
alert(stuff.chair); // alerts '10'
alert(stuff['chair']); // alerts '10'

stuff.house = 100000;
stuff['car'] = 10000;
alert(stuff['house']); // you get the picture...
alert(stuff.car); 

      



+2


a source


How about using a dictionary object:

var things = {'chair':10, 'tv':100, 'bed':75};
alert(things['chair'])

// if you want to use things['chair'].cost, it'd look more like this:
var things = {'chair': {cost: 10}, 'tv': {cost: 100}, 'bed': {cost: 75}};

      

+1


a source


use Why don't you define your arrays as an object like

var things = {'chair':10, 'tv':100, 'bed':75}

      

Then you can access prices like associative array properties

things.chair 

      

will give you 10

+1


a source


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);
}

      

0


a source


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);

      

0


a source







All Articles