本文介绍了将无序键分配给Js数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我得到一个随机键值对,我可以将它分配给数组吗?
I am getting a random key value pair,Can i assign it to an array?
在这里,当我像 arr [50] ='abc'
一样分配它时,它会产生问题,它会自动创建多达50个的键,例如 arr [0]
, arr[1]
, arr [2]
等.
Its problematic here when I assign it like arr[50] = 'abc'
it automatically creates the keys upto 50 like arr[0]
,arr[1]
,arr[2]
and so on.
并且我想要一个类似 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;
}
我在这里可以做什么?请让我知道.
What can i do here?Please let me know.
推荐答案
使用对象 {}
代替数组 []
.
对象可以充当无序键值容器,这似乎是您需要的.
Objects can act as unordered key-value containers, which is what you seem to be needing here.
// 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;
});
}
这篇关于将无序键分配给Js数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!