Is It Possible To Store Both A Number And Name For A Value In An Array?
Solution 1:
Absolutely!
In JS, you can make an array of any data type. You also have access to objects. So let's combine those.
var obj = {
name: 'a test name',
value: 1
}
vararray = [obj];
array[0].name; // == 'a test name'array[0].value; // == 1var anotherObj = {
name: 'another name',
value: 7
}
array.push(anotherObj);
array[1].name; // == 'another name'array[1].value; // == 7
Reading your question in more detail, I see you're also looking to have a get method that can pull from either value. That's a bit trickier.
The other answer provided will do this, but stores the data in two separate locations in the object (not an array), and also loses the array prototypes.
To better solve this within the Array class type, let's just take advantage of Array.filter!
array.filter(function(item) { return item.name === 'another name' })
This will provide you with a subArray of elements that meet whatever criteria you provide within the given callback function. In this case, using my array above, it would pass back an array with one element in it; anotherObj
.
Solution 2:
If you want to access by both, use object
var arr = {}
arr[1] = arr['myKey'] = 'myValue'
Then you can access them both by number and by key.
Post a Comment for "Is It Possible To Store Both A Number And Name For A Value In An Array?"