Conditional looping in JSON object
I`ve a JSON object and a loop
JSONobj.en.item[.....]
function dipslayItmes ( language )
{
...
for ( i = 0; i <开发者_C百科 JSONobj.en.item.length; i++ )
document.write( JSONobj.en.item[i] );
...
}
How to make it use language insted of directly use en ?
Whenever you do foo.bar
, you usually can do foo["bar"]
. However, not only can you put strings in the brackets, you can also put other expressions. Therefore, you can use this:
function displayItems(language) {
...
for(var i=0; i<JSONobj[language].item.length; i++) {
document.write(JSONobj[language].item[i]);
}
...
}
Use square bracket notation to use a string literal or value from a variable to reference a property:
function dipslayItmes ( language )
{
...
for ( i = 0; i < JSONobj[language].item.length; i++ )
document.write( JSONobj[language].item[i] );
...
}
精彩评论