0

I'm wondering for some time now why this fails:

if (longest.length >= 3) {
    for ( var i = 0; i < longest.length-1; i++) {
      var $last[i] = longest[i].splice(-1).toString();
      //if ( $( $last[i] ).closest(':jqmData(role="panel")') == "popover" ) { 
      //var gotoPage = $last[i];
    // }
      }
    }

longest is an array, which contains array elements.

I want to loop through the number of arrays in longest and create variables from each nested arrays' last element. The .splice(-1).toString() fails telling me "missing ; before statement"

What am I doing wrong?

EDIT: longest will look something like this:

[[#menu, #menuSub1, #menuSub2], [#main, yield, yield], [#pop1, #pop1-1, #pop1-2]]

It's within a function to track the browser-history in a mobile-app with different panels.

EDIT2: Finished code (Thx Mic):

if (longest.length >= 3) {
   var $last = [];
   for ( var i = 0; i < longest.length; i++) {
      $last.push( longest[i][ longest[i].length - 1 ]);
      if ( $( $last[i] ).closest(':jqmData(role="panel")').jqmData('panel')  == "popover" ) { 
         var gotoPage = $last[i]; }
      }
   }
4
  • should be the variable name. $last0, $last1, $last2... Commented Oct 21, 2011 at 19:18
  • I believe splice() requires two parameters, both being positive integers or zero. Commented Oct 21, 2011 at 19:21
  • You have one extra "}" out there, you probably forgot to comment out. Commented Oct 21, 2011 at 19:21
  • @Diodeus: I'm using it quite a lot, always like this, so I think that won't help. I think either chainging splice().toString() doesn't go or I can't declare variables like this: $last[i] Commented Oct 21, 2011 at 19:24

1 Answer 1

5

You should write something like:

if (longest.length >= 3) {
    var $last = [];
    for ( var i = 0; i < longest.length-1; i++) {
      $last.push( longest[i][ longest[i].length - 1 ] );
    }
  }

and get the values with $last[0]

Or use a hash like:

if (longest.length >= 3) {
    var hash = {};
    for ( var i = 0; i < longest.length-1; i++) {
      hash['$last'+ i] = longest[i][ longest[i].length - 1 ];
    }
  }

and get the content using for instance hash.$last0

4
  • may be give a sample of longest, it would help Commented Oct 21, 2011 at 19:27
  • I edited the answer, is it better? This is ok if you have just 2 levels of arrays, if you have more, it needs to recurse Commented Oct 21, 2011 at 19:31
  • longest.length-1 is a bit strange as you will never reach the last element of longest Commented Oct 21, 2011 at 19:33
  • Your first snippet works perfectly! THANKS. I'll probably be dreaming "array-style" tonight... Commented Oct 21, 2011 at 19:49

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.