问题描述
JavaScript有哪些使用数字索引 [约翰,鲍勃,乔]
和对象数组可以像关联数组或映射来使用的允许对象值字符串键{约翰:28,鲍勃:34,乔:4}
在PHP它是由值很容易被双方的 A)排序(同时保持键)和 B)试验在一个关联数组的值的存在。
$阵列= [约翰=> 28日,鲍勃=> 34,乔=> 4〕;ASORT($数组); // [乔=> 4,约翰=> 28日,鲍勃=> 34];如果(使用isset($阵列[会)){}
您将如何在Javascript达致这功能?
这是对于像加权列表或排序套东西,你需要保持在数据结构中的值的一个副本(如标签名称),并保持一个加权值的共同需要。
这是我想出来的迄今最好的:
函数getSortedKeys(OBJ){
VAR键= Object.keys(OBJ);
键= keys.sort(功能(A,B){返回物镜[α] -obj并[b]}); 变种地图= {};
对于(VAR I = keys.length - 1; I> = 0;我 - ){
图[键[I] = OBJ [键[I]];
}; 返回地图;
}VAR名单= {约翰:28,鲍勃:34,乔:4};
清单= getSortedKeys(名单);
如果(名单[会]){}
如果您使用的开源项目它很容易。
请参阅
VAR的结果= jinqJs()
。从([{约翰:28},{鲍勃:34},{乔:4}])
.orderBy([{领域:0}])
。选择();
Javascript has arrays which use numeric indexes ["john", "Bob", "Joe"]
and objects which can be used like associative arrays or "maps" that allow string keys for the object values {"john" : 28, "bob": 34, "joe" : 4}
.
In PHP it is easy to both A) sort by values (while maintaining the key) and B) test for the existence of a value in an associative array.
$array = ["john" => 28, "bob" => 34, "joe" => 4];
asort($array); // ["joe" => 4, "john" => 28, "bob" => 34];
if(isset($array["will"])) { }
How would you acheive this functionality in Javascript?
This is a common need for things like weighted lists or sorted sets where you need to keep a single copy of a value in data structure (like a tag name) and also keep a weighted value.
This is the best I've come up with so far:
function getSortedKeys(obj) {
var keys = Object.keys(obj);
keys = keys.sort(function(a,b){return obj[a]-obj[b]});
var map = {};
for (var i = keys.length - 1; i >= 0; i--) {
map[keys[i]] = obj[keys[i]];
};
return map;
}
var list = {"john" : 28, "bob": 34, "joe" : 4};
list = getSortedKeys(list);
if(list["will"]) { }
If you use the open source project jinqJs its easy.
See Fiddler
var result = jinqJs()
.from([{"john" : 28},{ "bob": 34},{ "joe" : 4}])
.orderBy([{field: 0}])
.select();
这篇关于如何实现地图或JavaScript中有序集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!