JavaScript 47. Iterating


#1



That is funny. But I get the answer I am asked to get. But the site tells me that it is incorrect.


var arr = ['one', 'two', 'three'];

// CORRECT
for (var i = 0; i < arr.length; i++) {
  var item = arr[i];
}

// BAD - this might not work as expected if
// other code has modified the Array prototype.
for (var key in arr) {
  var item = arr[key];
}

// Now, try using a for loop to create a string
// 'combined' that contains all the elements in
// the array put together.
function join(inputArray) 
{
  var combined = '';
  // Add for loop here
  for (i = 0; i < arr.length; i++)
  {
      var combined = combined + arr[i];
  }
  return combined;
}

// In this case, the output would be 'onetwothree'.
join(arr);


#2

I think that because they're asking you to iterate, you need a for each loop that would look like:

for item in inputArray {
    # do something to each item.
}

#3

@kyleaw, this is js, for in loop is for objects.

@megaslayer81031, you should loop over inputArray instead of arr, this way, your function will work for any array supplied as argument on the function call


#4

Ahh! You're right thanks for stepping in.


#5

@stetim94 Thank you, it worked!


#6