0

ランダムなキーと値のペアを取得しています。それを配列に割り当てることはできますか?

、などのようにarr[50] = 'abc'最大50個のキーを自動的に作成するように割り当てると、ここで問題になります。arr[0]arr[1]arr[2]

そして、私はこのような配列が欲しかった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;
                }

ここで何ができますか?教えてください。

4

1 に答える 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;
    });
}
于 2012-05-09T19:14:26.067 に答える