Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting error while printing through array in Java script

Tags:

javascript

I am using split function to remove the comma from an array which is displayed while using for loop to print an array but when i am using this code

 <script>
   var name = ["A", "B", "C"];
   var name_split = name.split(',')
   for(var i=0;i<name_split.length;i++)
   {
      document.write("\n",name_split[i],"\n");
   }
  </script>

I get the O/P for the above code as expected : A B C. But when i use the same code with different variables and some more methods it gives error,for instance this code

 <script>
   var intro = ["Hello","World","etc"];
   var intro_split = intro.split(',');
   for(var a=0;a<intro_split.length;a++)
     {
         document.write("\n",intro_split[a],"\n");
     }
 </script>

The error for this code is : TypeError: intro.split is not a function. Why is it happening ?

like image 353
Mehul Chachada Avatar asked Feb 23 '26 21:02

Mehul Chachada


1 Answers

'split' function is used for string, like this code:

var intro = "Hello,World,etc";
var intro_split = intro.split(',');
for(var i=0;i<intro_split.length;i++)
  {
     document.write("\n",intro_split[i],"\n");
  }

for printing array items use this code:

<script>
  var intro = ["Hello","World","etc"];
  for(var a=0;a<intro.length;a++)
  {
     document.write("\n",intro[a],"\n");
  }
</script> 
like image 129
MHS Avatar answered Feb 25 '26 11:02

MHS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!