2009-09-23 7 views
0

가 이미 저는 JQuery와 변수 클릭에JQuery와 JQuery와 메신저에

submitterid = 1 

에 저장 한 1의 첫 번째 요소를 선택

(1,2,6,8) 

같은 배열을 갖는 다음의 가장 큰 요소를 가져 오는 중 오류 링크 내가 submitterid에서 선택한 것보다 배열에서 다음으로 가장 큰 요소를 얻으려고합니다.

어떻게해야합니까?

편집 : 모든 배열을 보여주고 유지

var arr = [3, 5, 8, 3].sort(function (a, b) { return a - b; }); 
var val = arr.pop(); 

: 코드에서이 배열의 마지막 요소를 찾는 방법

var previousId; 

       $("#previous").click(function(){ 


      index = submitters.indexOf(submitterid), 
       nextId; 
      if (index - 1 < submitters.length) { 
       previousId = submitters[index-1]; 
      } else { 
       // no ID index 

       // if i am having an array of 1,2,6,8 after moving to 1 from 8 to 6 - 2-1 i am trying to move to the last element of the array 
      } 

      alert(previousId); 




     });// previousId 
+0

jquery에서 javascript로 retaged되었습니다. –

답변

4

가 왜 그런 짓을 할 수 없습니다 - 값이 배열에 머물러있을 필요가 없다고 말합니다.

값을 무작위로 선택하고 그 중 가장 높은 값이 필요한 경우 적절한 정렬 함수를 작성하십시오.

+4

기본 비교 함수이므로 비교 함수를 지정할 필요가 없습니다. – Gumbo

+0

그것은 증명하는 것이 었습니다 :) –

0

배열을 반복해야합니다. 단지 '일반 자바 스크립트'할 것을 처리하는 클릭 이벤트에서 떨어져,이를 위해 어떤 JQuery와 특정 물건을 사용할 필요가 없습니다, 사실

// Your test array. 
var arrValues = [ "1", "2", "6", "8" ]; 

var low = 1; 
var high = 2; 

// Loop over each value in the array. 
$.each(arrValues, function(intIndex, objValue){ 

if (objValue > high) 
    hight = objValue; 

if (objValue < high) 
    if (objValue > low) 
    low = objValue 

}); 

return low; 
+0

저스틴의 코드 또한 좋은 생각이었습니다. 배열을 가장 높은 순서로 정렬하십시오. 마지막 요소의 위치를 ​​찾고 마지막 요소를 반환하십시오. – Steven

0

; 이 테스트되지 않은 코드를 사용해보십시오 좋아 당신은 그것을 인스턴스화하고 사용

function counter(arr) { 
    this.arr = arr; 
    this.index = 0; 
} 

counter.prototype.next = function() { 
    return this.arr[this.index++]; 
} 

: 배열이 이미 정렬

var nums = new counter([1,2,3,4,5]); 
nums.next() ; => 1 
nums.next() ; => 2 
nums.next() ; => 3 
1

당신은 카운터를 원하는
var arr = [1,2,6,8], 
    submitterid = 1, 
    index = arr.indexOf(submitterid), 
    nextId; 
if (index + 1 < arr.length) { 
    nextId = arr[index+1]; 
} else { 
    // no ID index 
} 
+0

숫자가 이미 낮은 순으로 정렬되어 있다고 가정하지 않으시겠습니까? 숫자는 1,6,3,9,7이 될 수 있습니다. – Steven

+0

나는 묻는 사람이 어떻게 정렬 하는지를 알고 싶지 않다고 생각한다; 나는 그가 다음으로 큰 지수를 원한다는 것을 의미한다고 생각한다. 그의 배열은 예제에서 이미 정렬되어 있습니다. –

0

경우 (sort method 참조),이 시도 :

var myArray = [ 1, 2, 6, 8 ]; 
var submitterid = 1; 

$(function() { 
    $('a#id').click(function(event) { 
    event.preventDefault(); 
    var greater = -1; 
    // loop through array 
    for (var i in myArray) 
     // find numbers greater than the specified number 
     if (i > submitterid) 
     // find numbers closest to specified number 
     if (i < greater || greater < 0) 
      greater = i; 

    if (greater < 0) { 
     // no greater value found, do something 
    } else { 
     // next biggest value is in variable greater, do something with it 
    } 
    }); 

}); 
+0

이전 편집을 참조하십시오. – useranon

+0

@Aruna : 'index + 1 = 0'으로 바꾸고'nextId = arr [index + 1]'을'prevId = arr [index-1]'. – Gumbo