0

Isn't there any ways for converting array-like objects into array so that all array methods can be used with it?see here:

[].prototype.forEach.call("maizere",fn)

likewise for every array-like objects,

what i want is ,to use forEach loop directly on this "maizere" string.But before that i need to convert it into an array .Is there any possibility or any trick that works for all array-like objects.Thank u.

5
  • Do you really need a single solution that works for all different types, or just strings? Commented Jun 21, 2013 at 16:44
  • What type of function might be called with either a string, NodeList, arguments, etc. and needs to process them all as arrays? This seems like a strange requirement. Commented Jun 21, 2013 at 16:46
  • @Barmar not strange,i just want to use all array method into array-like objects without any deeper code but apply directly on them.So is there any method or trick that will convert array-like objects to array .So that i can use that method/trick whenever i want to use array-like objects as array and use array methods without any fear Commented Jun 21, 2013 at 16:48
  • You're not satisfied with the answer that Blender gave? I don't know anything better. Commented Jun 21, 2013 at 17:00
  • everybody here seems to know what the term "array-like object" referes to, cool. For understanding the question better, what is it. I woudl be nice to give a reference to what is meant by "array-like object". Maybe this then also would help in even making clearer the question. Thank you Commented Nov 6, 2013 at 15:01

1 Answer 1

2

Pass it into slice instead of forEach (slice will just make an array out of it):

Array.prototype.slice.call("maizere").map(function(l) {
    return l + 'foo';
}).forEach(function(l) {
    console.log(l);
});

It'll work for array-like objects like NodeLists, arguments and strings.

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

1 Comment

thank u ,that was helpful.Also will this method work for any arry-like object

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.