Click here to Skip to main content
15,894,410 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i'm having problems with the code i made below
i'm not sure whats wrong with it, could someone hint me

JavaScript
var myarr = ['tpc001:10','tpc003:5','tpc000:4','tpc001:7','tpc003:4','tpc008:1'];
var sumarr =[];  // i create an empty array
myarr.sort();    // sorting myarr

sumarr.push(myarr[1]); // add first element of myarr to sumarr.


alert(sumarr[1]);   // error undefinied, but i just pushed a string value to it ??
Posted

1 solution

OK, I'll give you a hint. Indices start from zero (0) in javascript. So if you have an empty array like sumarr in your example and then push one element onto that array (LIFO fashion) how many elements are now in the array?
If there are m elements in an array and one wants to get at the mth element with 0 < m <= n the index of that element will be m-1.

Cheers!

—MRB
JavaScript
var myarr = ['tpc001:10','tpc003:5','tpc000:4','tpc001:7','tpc003:4','tpc008:1'];
var sumarr =[];  // i create an empty array
myarr.sort();    // sorting myarr

sumarr.push(myarr[1]); // add the second element of myarr to sumarr.


alert(sumarr[0]);   // Since there is only one element in sumarr that's all you will get here
 
Share this answer
 
v2
Comments
PGT 15-Nov-11 4:31am    
Ah i got confused in multiple ways
the sort command made that tpc001 is actually element number 1 not zero
another thing that got me confused is that if you do
document.write(sumar.push[1]);) >> wil output 1
therefor i was thinking it would show its index number
but it doent it show the length which 1

thanks for your help i was looking to long at it; got confused
Manfred Rudolf Bihy 15-Nov-11 7:04am    
I'm glad if it helped you. :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900