UFO ET IT

JQuery, 값이 배열에 존재하는지 확인

ufoet 2020. 12. 13. 10:01
반응형

JQuery, 값이 배열에 존재하는지 확인


이 질문에 이미 답변이 있습니다.

나는이 질문이 자바 스크립트 / jquery로 놀았 던 사람들에게 상당히 쉬울 것이라고 믿습니다.

var arr = new Array();

$.map(arr, function() {
 if (this.id == productID) {
   this.price = productPrice;
 }else {
  arr.push({id: productID, price: productPrice})
 }
}

위의 코드는 내가 원하는 것을 정말 간단하게 설명한다고 생각합니다. 이 $ .map이 이와 같이 작동 할 것이라고 생각하지만 불행히도 결과를 얻을 수 없었습니다.

이를 수행하는 가장 간단하고 우아한 방법은 무엇입니까? 키의 값이 있는지 여부를 찾기 위해 모든 배열을 정말로 검토합니까?

Jquery에는 다음과 같은 것이 isset($array['key'])있습니까?

편집하다

inArray를 사용하려고했지만 일치하는 항목이 있어도 배열에 개체를 계속 추가합니다.

if ( $.inArray(productID, arr) > -1) {
   var number = $.inArray(productID, arr);
   orderInfo[number].price = parseFloat(productPrice);
}else {
   orderInfo.push({id:productID, price:parseFloat(productPrice)});
}

사용 .map()하거나 작동 방식을 알고 싶다면 다음과 같이 할 수 있습니다.

var added=false;
$.map(arr, function(elementOfArray, indexInArray) {
 if (elementOfArray.id == productID) {
   elementOfArray.price = productPrice;
   added = true;
 }
}
if (!added) {
  arr.push({id: productID, price: productPrice})
}

이 함수는 각 요소를 개별적으로 처리합니다. .inArray()다른 답변에서 제안 아마 그것을 할 수있는 더 효율적인 방법입니다.


http://api.jquery.com/jQuery.inArray/

if ($.inArray('example', myArray) != -1)
{
  // found it
}

jQuery에는 다음과 같은 inArray기능이 있습니다.

http://api.jquery.com/jQuery.inArray/


    if ($.inArray('yourElement', yourArray) > -1)
    {
        //yourElement in yourArray
        //code here

    }

참조 : Jquery 배열

$ .inArray () 메서드는 일치하는 항목을 찾지 못하면 -1을 반환한다는 점에서 JavaScript의 기본 .indexOf () 메서드와 유사합니다. 배열의 첫 번째 요소가 값과 일치하면 $ .inArray ()는 0을 반환합니다.


시험 jQuery.inArray()

다음은 동일한 코드를 사용 하는 jsfiddle 링크입니다 . http://jsfiddle.net/yrshaikh/SUKn2/

$ .inArray () 메서드는 일치하는 항목을 찾지 못하면 -1을 반환한다는 점에서 JavaScript의 기본 .indexOf () 메서드와 유사합니다. 배열의 첫 번째 요소가 값과 일치하면 $ .inArray ()는 0을 반환합니다.

예제 코드 :

<html>
   <head>
      <style>
         div { color:blue; }
         span { color:red; }
  </style>
      <script src="http://code.jquery.com/jquery-latest.js"></script>
   </head>
   <body>    
      <div>"John" found at <span></span></div>
      <div>4 found at <span></span></div>
      <div>"Karl" not found, so <span></span></div>
      <div>
         "Pete" is in the array, but not at or after index 2, so <span></span>
      </div>
      <script>
         var arr = [ 4, "Pete", 8, "John" ];
         var $spans = $("span");
         $spans.eq(0).text(jQuery.inArray("John", arr));
         $spans.eq(1).text(jQuery.inArray(4, arr));
         $spans.eq(2).text(jQuery.inArray("Karl", arr));
         $spans.eq(3).text(jQuery.inArray("Pete", arr, 2));
      </script>  
   </body>
</html>

Output:

"John" found at 3
4 found at 0
"Karl" not found, so -1
"Pete" is in the array, but not at or after index 2, so -1

참고URL : https://stackoverflow.com/questions/7880972/jquery-checking-if-a-value-exists-in-array-or-not

반응형