Reputation: 1205
Recently I am learning to make javascript class, I saw other people make class like this
var item = {
'a':{'b':1000,'c':2000,'d':3000} , //how to make a variable become an array?
myfunction : function(){
console.log(item.a.b); //and output item.a[1]?
}
};
item.myfunction();
But is it possible to make variable a
an array? and output a variable item.a[1]
like that?I tried
var a=new Array('1000','2000','3000')
but error, I need a correct syntax.
Upvotes: 1
Views: 2749
Reputation: 85767
var item = {
'a': [1000, 2000, 3000],
myfunction: function () {
console.log(this.a[1]);
}
};
But that's not a class, and there is no "variable a".
Upvotes: 2
Reputation: 370
You have 2 ways depending on if you want to convert "a" to an array or if you just want "a" to be an array.
The first method would be to run it through a function
function toArray(object) {
var array = new array();
for (key in object) {
if (object.hasOwnProperty(key)) {
array.push(object); // This is alternative for indexed array
array[key] = object; // This is for an associative array
}
}
return array;
}
Maybe have your "class" call this function and assign the return value to "a"
var item = {
'a':{'b':1000,'c':2000,'d':3000} , //how to make a variable become an array?
myfunction : function(){
this.a = toArray(this.a);
console.log(this.a[1]) // If you do indexed
console.log(this.a.b); // If you do associative
}
};
item.myfunction();
The second way was explained by @ahren which is just to define "a" as an array by [...] the values instead of {...}
You can also check out my own question put up about OOP in JavaScript, got a nice reply from T.J. about it there concerning private methods.
Don't know if this is what you wanted but should work.
Upvotes: 0
Reputation: 16961
'a':[1000,2000,3000]
console.log(item.a[0]); // 1000
console.log(item.a[2]); // 3000
Read more: http://www.elated.com/articles/javascript-array-basics/
Upvotes: 1