-1

When i run below code

<script>

    var name = "Hello moorthi";
    var myArray = name.split(' ');

    setTimeout(function(){
      var nameDisplay='';
      try {
        for (var names in myArray){

          nameDisplay += myArray[names].toUpperCase()+' ';
        }
        alert(nameDisplay);
      }
      catch(err){
        console.log(err.message);
      }
    },
    1000);

 </script>

getting undefined is not a function error in chrome, can help me why this happening?

Moorthi
  • 11
  • 8
  • 3
    do not use a for in loop to loop an array. – epascarello Jul 01 '14 at 16:32
  • can you give me solution on this – Moorthi Jul 01 '14 at 16:33
  • The solution is to stop using a for-in loop. – user2357112 Jul 01 '14 at 16:34
  • The array traversal is irrelevant to the error here. @user3791235: I can run your code fine here: http://jsfiddle.net/T4xYS/. Is the code you post *actually* the code that you're running? – Dancrumb Jul 01 '14 at 16:45
  • Yes Dancrumb, but it's going to break... Why? – Moorthi Jul 01 '14 at 16:48
  • What do you mean "it's going to break"? – Dancrumb Jul 01 '14 at 18:56
  • Oh... is this a homework question? – Dancrumb Jul 01 '14 at 18:57
  • @YungGun And I too make comments on questions from 5 years in the past. And comments are not freaking answers. Sorry I made a statement to not do something that was causing the issues. There are times when I do not have 5 minutes to write an answer so I make a quick statement and hopefully someone that has time makes the answer with the details. That is how I been doing it on stackoverflow for the last 11 years. And the correct answer today would be use map. – epascarello Dec 18 '19 at 16:23

2 Answers2

1

Use

msgupdate = myArray.map(function (i) { return i.toUpperCase() }).join(' ');

Using for/in isn't a good idea, without a hasOwnProperty check.

user229044
  • 232,980
  • 40
  • 330
  • 338
1

I'm not sure this will guarantee the order of the elements in the array. The best solution would be to go with a for loop (both for performance and order):

for (var i=0, len=myArray.length; i<len; i++){
      msgupdate += myArray[i].toUpperCase()+' ';
}
javinor
  • 674
  • 4
  • 8