0

Of the following examples, the top two return [object, object], but the third returns what I would expect from the first two, which is "Next"

alert(sceChoicesArr);

alert(sceChoicesArr[0]);

alert(sceChoicesArr[0].text());

Here's the array being created:

var sceChoicesArr = [];

$(xml).find('choice').each(function(){sceChoicesArr.push($(this));});

And here's the bit of xml it's looking for in the line above:

<choice>Next</choice>

I'm trying to spit out the array into html, and I keep writing things out off examples like the ones on this page: Display all items in array using jquery as well as this: http://jsfiddle.net/chrisabrams/hYQm4/ but none of these examples seem to be able to pull out the value inside the array, as when I check it out with an alert, all I'm getting is [object, object]

So my question is, what is [object, object], and why am I getting that instead of "Next"?

It seems to me that the only value of my array should equate to ["Next"]

Community
  • 1
  • 1
Eric
  • 2,004
  • 6
  • 23
  • 33

1 Answers1

1

In your code, you are using sceChoicesArr.push($(this));. Which is pushing a jQuery object to the array.

alert is implicitly calling Object.prototype.toString with sceChoicesArr, which when called on an object, returns "[object Object]".

Instead of using:

sceChoicesArr.push($(this));

use:

sceChoicesArr.push($(this).text());

And then to get the array in a "readable" form:

sceChoicesArr.join(", ")

Or continue pushing $(this), and then to get a "readable" form, use:

var readableArr = $.map(sceChoicesArr, function (value, index) {
    return $(value).text();
});

which will return a new array with only the text of each element. Then just use:

readableArr.join(", ")

If you only want to view the contents of your array (and not use it anywhere else), you can use console.log(sceChoicesArr); which should provide a useful overview of your variable.

Ian
  • 50,146
  • 13
  • 101
  • 111
  • @adeneo You don't give me enough time :) And I wasn't sure if they wanted to see its contents from a developer's standpoint (looking at the screen) or needs it somewhere else in the code/page – Ian Apr 03 '13 at 19:51