开发者

Select element from json dynamically

I have a an associative array in php that i parse to get json from it (json_encode) then i store the result in a javascript var

var myArray = <?php p开发者_StackOverflow社区rint json_encode($phpArray); ?>;

Now whene the user hit a button i should choose another element from the array dynamically, for example, i chose a random first element :

var an_element = myArray.a2.link;

-'a2' is an array in the main array

-'link' is an element in the a2 array.

So now whene the user hit my button, i want to choose a random other array id (for example a5, a9, etc.) I tried this :

var randomnumber=Math.floor(Math.random()*101); // choose random number
var newRandomArrayID= "a"+randomnumber;
an_element = myArray.newRandomArrayID.link;

It doesn't works, it says myArray.newRandomArrayID is undefined. Anyone can help? Thank you


You need to use [] indexing to find properties by name:

an_element = myArray[newRandomArrayID].link;

Otherwise JS is looking for a property actually called newRandomArrayID on myArray rather than using the value of the variable to lookup the property.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜