How to remove quotes from string so that it can be used for an associative array [closed]

StackOverflow https://stackoverflow.com/questions/22783550

Вопрос

I want to be able to take a string from an array an using an associative array get some statistics for that subject.

var subjects = ['Biology','English'];
var HBio = [5.8,8.6,7.4,9.5,10.4,8.8,9.2,9.9,7.2,7.1,7.8,6.5,1.5,2.2];
var h = new Object();
h['Biology'] = HBio;
array=h.Subjects[0];

The problem is that the string at Subjects[0] has quotes and so I can't use array=h.Subjects[0], is there any way to work around this? or should I try something else?

Это было полезно?

Решение

You want

var array = h[subjects[0]];

not

array = h.Subjects[0];

FIDDLE

Другие советы

Instead of h.Subjects[0] you have write this h[subjects[0]] then your code will be

var subjects = ['Biology','English'];
var HBio = [5.8,8.6,7.4,9.5,10.4,8.8,9.2,9.9,7.2,7.1,7.8,6.5,1.5,2.2];
var h = new Object();
h['Biology'] = HBio;
array=h[subjects[0]]; //result will be [5.8, 8.6, 7.4, 9.5, 10.4, 8.8, 9.2, 9.9, 7.2, 7.1, 7.8, 6.5, 1.5, 2.2] 

reason behind this is, when you write h.subjects[0]. This means that you h is an object having key 'subjects' and which contain an array. But actually we have h an object which have key biology and it contain an array of values, whereas subjects is an array contain name of subjects. So to get values using both, first we have to get value from subjects array like this subjects[0] then put this value in h like this h[subjects[0]]. Now what it will do is first get 0 index of subjects i.e. 'Biology' then get value of key Biology from object h. I hope it will clear issue and worth it to you. Thank you

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top