2012-05-09 2 views
0

임의의 키 값 쌍을 가져옵니다. 배열에 할당 할 수 있습니까?정렬되지 않은 키를 Js 배열에 할당

그것 여기에 문제가 내가 arr[50] = 'abc'처럼 할당 할 때 자동으로 등등 arr[0], arr[1], arr[2]과 같은 50 개까지의 키를 생성합니다.

그리고 난이 arr[50=>'abc','40'=>'pqr','53'=>'lmn']

같은 배열을 원하는 내가 여기 내가 여기서 무엇을 할 수

if(typeof(feedArr.latestRating) == 'object'){ 
        jQuery.each(feedArr.latestRating,function(key,val){alert('key::'+key); 
        if(key in newRatingArr){ 
        //delete the key if already exists 
         newRatingArr.splice(key,1); 

        }else{ 
         //insert the key,value 
         newRatingArr[key] = val; //here is the problem occurs when key is 50 it automatically creates the indexes in the array upto 50 which i dont want 
         // alert('Key between::'+key); 
         // alert('Value between::'+newRatingArr[key]); 
         //newRatingArr.splice(key,0,val); 
        } 
        //alert(key); 
        emptyRate = 0; 

        }); 
       }else{ 
        emptyRate = 1; 
       } 

그것을 가지고? 알려 주시기 바랍니다.

답변

5

대신 {} 개체를 사용하십시오.

개체는 순서가 지정되지 않은 키 - 값 컨테이너로 작동 할 수 있습니다. 이는 사용자가 여기에서 필요로하는 것입니다.

// somewhere... 
var newRatingArr = {}; 

// your code. 
var emptyRate = true; 
if (typeof (feedArr.latestRating) == 'object') { 
    jQuery.each(feedArr.latestRating, function (key, val) { 
     newRatingArr[key] = val; 
     emptyRate = false; 
    }); 
} 
+0

SPLICE와 같은 다른 기능도 모두 개체에서 작동합니까? AKX? –

+0

concat 및 shuffle과 같은 다른 배열 함수는 여기에서 객체를 사용하면 덜 사용됩니다. AKX –

+0

하지만 배열과 같은 연속 데이터가 없으면 배열로 강제해서는 안됩니다 ... – AKX

관련 문제