[Solved] Array iteration in javascript

Introduction

Solution


So I know you are talking about arrays in your post but your “array” you give to us is actually an object. Major shocker, I know… Notice the array [ ] vs object { } brackets.

But this isn’t actually a bad thing in your case. You won’t need to loop over all items in an array at all!! Let me show you.

You can access the keys of the object by array notation in javascript. (still following?) The basic way to do that is:

object['key']           //accessing by array notation

or

object.key              //accesing by dot notation

And since you’re talking about returning, I’m presuming your talking about functions. Take a look at the following search function using a check on the object named collection with array notation

var collection = {3412124539: 1, 3412124540: 1, 3412124577: 2, 3412124590: 1, 3412124602: 1, 3412124605: 1, 3412124607: 1, 3412124617: 1, 3412124629: 1, 3412124630: 1, 4709502367: 1, 4709502349: 1, 4709502326: 1, 4708510268: 1, 4708510060: 1}

function search(inWhat, forWhat, equalsWhat){
  if(inWhat[forWhat] == equalsWhat)
    return 'returned cause '+forWhat+' is '+equalsWhat;
}

var returnValue = search(collection, 3412124577, 2);

// ---- outputting the returnValue here
document.write(returnValue);

0