Pregunta

There are lots of questions like this but...duh...I can't get it to work. How do I...take an object literal like this:

locations = {};

locations.activities = [
{ text:'biking'},
{ text:'hiking'},
{ text:'boating'},
{ text:'studying'},
{ text:'reading'},
];

And print out the activities array values?

IE and Firefox are getting different lengths (6 and 5 respectively).

Thanks

¿Fue útil?

Solución

The problem is the trailing comma: remove it for cross-browser compatibility reasons.

The inconsistent behavior is caused because some browsers parse the literal incorrectly1 when a trailing comma is present. The correct behavior is to ignore the trailing comma2:

If an element is elided at the end of an array (i.e. [...,]), that element does not contribute to the length of the Array.


1 The syntax works correctly in IE10 but incorrectly in IE9 and before. This can be verified by testing [1,].length from the console in the relevant browser mode. The values reported are 1 (correct) and 2 (incorrect), respectively.

2 The trailing comma is relevant in the case of [,] which should be equivalent to [undefined].

Otros consejos

Use JSON.stringify(locations.activities);

try this

locations = {};
locations.activities = [
{ text:'biking'},
{ text:'hiking'},
{ text:'boating'},
{ text:'studying'},
{ text:'reading'},
];


 $.each(locations.activities, function(){
  alert(this.text);
 }); 

js fiddle here http://jsfiddle.net/mhnHx/

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top