1

In the following example:

HTML:

<ul>
  <li id="0"></li>
  <li id="213"></li>
  <li id="324"></li>
  <li id="764"></li>
</ul>

JS:

var map = $("ul").children().map(function(i, el) {
  return el.id;
});

console.log(Array.prototype.slice.call(map).join(":")); // 0:213:324:764 
console.log(map.join(":")); //error: Uncaught TypeError: undefined is not a function 

The map function will error if trying to use native array methods,

if you parse the returned jq 'array' into a normal array - everything works.

What could be the reason to it?

Fiddle: http://jsfiddle.net/hQZqU/1/

silicakes
  • 6,364
  • 3
  • 28
  • 39
  • 1
    A jquery object is not an array and therefore doesn't have a `join` method. Call `.get()` first to convert the an array from the jquery object. – Felix Kling Jun 16 '14 at 14:16
  • http://jsfiddle.net/ue2zc use `map.get().join(":")` @FelixKling comments pretty much sums up thing – Satpal Jun 16 '14 at 14:16
  • thank you, but what baffles me is that the structure is array like, i,e: [val, val, val]. Is it possible to mimic such structure in JS without it being an array? – silicakes Jun 16 '14 at 14:18
  • Seems to me like you should use `$.map` instead if you want an array and not a jQuery collection -> **http://jsfiddle.net/hQZqU/3/** – adeneo Jun 16 '14 at 14:29
  • 1
    Yes. Every object that has numeric properties and a `.length` property is an array-like object. And thinking about it, since a jquery object usually contains DOM elements, what should happen when you concatenate them with a string? – Felix Kling Jun 16 '14 at 14:42
  • 1
    More on array like objects here: http://stackoverflow.com/questions/1483445/how-do-jquery-objects-imitate-arrays – shem86 Jun 16 '14 at 14:46

2 Answers2

3

Your selector is a jQuery object ($("ul").children()), so map return this jQuery list of objects :

jQuery("0", "213", "324", "764")

In order to have an array, you have to use toArray :

console.log(map.toArray().join(":"));

You can look at this fiddle : http://jsfiddle.net/hQZqU/2/

Samuel Caillerie
  • 8,259
  • 1
  • 27
  • 33
0

.map() will return jquery object but .get() on the result to work with a basic array.

var map = $("ul").children().map(function(i, el) {
    return el.id;
}).get();

jsfiddle demo

Md Nazmoon Noor
  • 3,187
  • 1
  • 24
  • 30