0

This is the html part for my problem

<DIV ID="CONTAINER">
    <DIV CLASS="ITEMS">
        Purchase
    </DIV>
    <DIV CLASS="ITEMS">
        Return
    </DIV>
    <DIV CLASS="ITEMS">
        On Hold
    </DIV>
    <DIV CLASS="ITEMS">
        Exchange
    </DIV>
</DIV>    

Jquery

var MyArray = [];  
var $Items = $('.ITEMS');
$Items.each( 
  function(){
    Value = $.trim($(this).html());
    MyArray.push(Value);
  }
);
var Count_Parts = MyArray.length;            
for (i = 1; i <= Count_Parts; i++ ){
  console.log(MyArray[i]);
}

My Problem is that the console does not show correct results i see Return, On Hold, Exchange, undefined..... It is skipping Purchase and showing undefined instead? Why is Purchase being undefined?

2

2 Answers 2

1

Your code for the most part is correct, it is pushing the correct value for all items into the array. The for loop you are using is not iterating as you expect. If you look at this line:

for (i = 1; i <= Count_Parts; i++ ){

You are starting the loop at the number 1 and asking it to stop when it is less than or equal to Count_Parts (which is is 4). Now when you access elements in the array you are accessing elements 1,2,3,4. The array however begins at 0, and has elements stored at 0,1,2,3.

The correct implementation would be:

for (i = 0; i < Count_Parts; i++ ){

This starts your loop at 0 and will only run while i is less than the count. So it will access, 0,1,2,3 which is where the array has all elements stored.

The complete portion of your code with the correction is:

var MyArray = [];  
var $Items = $('.ITEMS');
$Items.each( 
  function(){
    Value = $.trim($(this).html());
    MyArray.push(Value);
  }
);
var Count_Parts = MyArray.length;            
for (i = 0; i < Count_Parts; i++ ){
  console.log(MyArray[i]);
}

JsFiddle: http://jsfiddle.net/MQBnW/

Sign up to request clarification or add additional context in comments.

1 Comment

thank you for explaining in such great detail i will like your answer when i am allowed
0

Array index starts from 0...(length -1 )

var Count_Parts = MyArray.length;            
for (i = 0; i < Count_Parts; i++ ){
  console.log(MyArray[i]);
}

Demo: Fiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.