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/

6
  • 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. Commented Jun 16, 2014 at 14:16
  • jsfiddle.net/ue2zc use map.get().join(":") @FelixKling comments pretty much sums up thing Commented Jun 16, 2014 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? Commented Jun 16, 2014 at 14:18
  • 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? Commented Jun 16, 2014 at 14:42
  • 1
    More on array like objects here: stackoverflow.com/questions/1483445/… Commented Jun 16, 2014 at 14:46

2 Answers 2

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/

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.