0

I tried using the join() function in my array and tried to document.write it but the console says"birth.join() is not a function "

birthyear=[];

for(i=1800;i<2018;i++){
birthyear+=i
}

birth=birthyear.join();

document.write(birth);

3 Answers3

2

Array.prototype.join() works on array and to insert an element to array you should call .push() instead of +=, read more about += here.

Always use var before declaring variables, or you end up declaring global variables.

var birthyear = [];

for (i = 1800; i < 2018; i++) {
  birthyear.push(i);
}

var birth = birthyear.join(", ");

document.write(birth);
void
  • 36,090
  • 8
  • 62
  • 107
1

I your code your not appending data to array you are adding data to array variable which is wrong

1st Way

birthyear=[]; 
for(i=1800;i<2018;i++)
{ 
    birthyear.push(i); 
} 
birth=birthyear.join(); 
document.write(birth);

2nd Way

birthyear=[];
k=0;
for(i=1800;i<2018;i++){
birthyear[k++]=i;
}

birth=birthyear.join();

document.write(birth);
Jay Shankar Gupta
  • 5,918
  • 1
  • 10
  • 27
0

You can't apply .push() to a primitive type but to an array type (Object type). You declared var birthyear = []; as an array but in the body of your loop you used it as a primitive: birthyear+=i;.

Here's a revision:

var birthyear=[];

for(let i=1800;i<2018;i++){
    birthyear[i]=i;  
   // careful here:   birthyear[i] += i; won't work 
   // since birthyear[i] is NaN
}

var birth = birthyear.join("\n");

document.write(birth);

Happy coding! ^_^

Christian Hur
  • 429
  • 3
  • 10