0

I have a small question which troubled me one afternoon.yes I'm new to JavaScript and so sorry for asking a easy question,I think I won't sleep if I can't figure out this bug.Here is the cade:

var a = [1, 3, 5, 7, 5, 3];
console.log(a);
/*Array[6]
0:1
1:3
2:3
3:5
4:5
5:7*/
alert(a);//1,3,5,7,5,3
var b = a.sort();
console.log(a);
/*Array[6]
0:1
1:3
2:3
3:5
4:5
5:7*/
alert(a);//1,3,3,5,5,7

I dont understand why "console.log(a)" had sorted before I call function.But alert run well.Thanks so much for answering.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
UTRANANA
  • 3
  • 1

1 Answers1

1

Maybe you got confused because you log your array twice. I hope the snippet below clarifies this a bit:

var a = [3, 1, 2];
console.log('before', a);
a.sort();
console.log('after', a);
Christian Zosel
  • 1,424
  • 1
  • 9
  • 16
  • thank you very much!I have this question because I open a new page every time. And this time I refreshed the screen ,the output is right.It seems that I have to refresh the screen every time?Do you know why ? – UTRANANA Dec 08 '16 at 07:19
  • I'm not quite sure what you mean. Do you open a new browser tab? And by refreshing the screen, you mean refreshing the website you're on? – Christian Zosel Dec 08 '16 at 08:26
  • yes,that is what I want to say. When I open a new browser tab,the output is false.Then I refresh the website,the output is true. – UTRANANA Dec 08 '16 at 14:29
  • False and true? Currently, you're just logging the sorted/unsorted arrays. Maybe you should ask another question and also post some information on how you run your JS, HTML, etc. – Christian Zosel Dec 08 '16 at 15:00
  • OK.thank you for the suggestions. – UTRANANA Dec 09 '16 at 07:25