开发者

Array read problem for map of vectors of strings in javascript

I am a newbie in JS. Here is my code and I believe it should work... but it doesn't.

var pop = new Array();
pop['la'] = new Array('nt','gb','te');
开发者_JAVA百科pop['sa'] = new Array('nt','gb');
pop['ha'] = new Array('pc','pa');
var _ecpop="la";

for (var i = 0; i < pop[_ecpop].length; i++)
{
    document.write(pop[_ecpop][i]);
}

I just do not know any alternate way to have a map of vectors of a string.

Thanks,

Amir.


That's not an Array, but a Javascript Object, containing Arrays in it's properties. You can use Object and Array literals for that. The advantage is that your code looks much cleaner. There are seldom reasons to use new Array or new Object in javascript code (see for example this SO Question).

var pop = {
  la: ['nt','gb','te'],
  sa: ['nt','gb'],
  ha: ['pc','pa']
}

now you can use

for (var i = 0; i < pop.la.length; i++) { 
 console.log(pop.la[i]);
} 

if a property label is stored in a variable (like you _ecpop), you can use bracket notiation to retrieve it's value:

var laArr = pop[_ecpop];
for (var i = 0; i < laArr.length; i++) { 
 console.log(laArr[i]);
}

The other way around you can assign a label to an Object:

var _ecpop = 'la';
pop[_ecpop] = ['nt','gb','te'];

document.write is not the preferred way to put things on your page. It's better and just as easy to use some element with an id, and write output to it using innerHTML, for example

document.getElementById('myOutput').innerHTML = '[some output here]';


In javascript, an array can only have numeric indexes, if you want to use textual indexes, you should use object instead.

var pop = new Object();

or

var pop = {};

and then:

pop['la'] = new Array('nt','gb','te');

However, as an object is not an array, it has no length member, but just as an array you can use the for..in to go through all of its values.

Using document.write is not a good choice as it only works during the document loading, not after it. Try to use text nodes or innerhtml instead.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜