bha*_*629 7 javascript arrays sorting
我已经定义了一个对象
var Person = function(name,age,group){
this.name = name,
this.age = age,
this.group = group
}
var ArrPerson = [];
ArrPerson.push(new Person("john",12,"M1"));
ArrPerson.push(new Person("sam",2,"M0"));
Run Code Online (Sandbox Code Playgroud)
现在我需要一种有效的机制来识别ArrPerson对象数组是否包含特定名称?
我知道我们可以使用for循环和check来迭代数组.假设数组很大,有没有其他有效的方法呢?
您可以使用数组过滤器或查找方法
ArrPerson.find(p=>p.name=='john')
ArrPerson.filter(p=>p.name=='john')
Run Code Online (Sandbox Code Playgroud)
find方法从开始时搜索数组,并在找到一个匹配的元素时停止.在最坏的情况下,被搜索的元素是数组中的最后一个或者它不存在,这个方法将执行O(n).这个意味着此方法将执行n次检查(n作为数组的长度),直到它停止.
filter方法总是执行O(n),因为每次它将搜索整个数组以找到匹配的每个元素.
虽然您可以通过创建新的数据结构来更快地(理论上)创建更多内容.例如:
var hashmap = new Map();
var ArrPerson = [];
ArrPerson.push(new Person("john",12,"M1"));
hashmap.set("john",true);
Run Code Online (Sandbox Code Playgroud)
这个ES6 Map将根据它包含的名称保留整个数组的索引.如果你想查看你的数组是否包含一个名字,你可以这样做:
hashmap.has('john')//true
Run Code Online (Sandbox Code Playgroud)
这种方法将执行O(1).只需在地图中检查一下,看看数组中是否存在此名称.您还可以跟踪地图中的数组索引:
var index = ArrPerson.push(new Person("john",12,"M1"));
var map_indexes = hashmap.get("john");
if(map_indexes){
map_indexes.push(index-1);
hashmap.set("john",map_indexes);
}else{
hashmap.set("john",[index-1]);
}
map_indexes = hashmap.get("john"); //an array containing the ArrPerson indexes of the people named john
//ArrPerson[map_indexes[0]] => a person named john
//ArrPerson[map_indexes[1]] => another person named john ...
Run Code Online (Sandbox Code Playgroud)
使用这种方法,您不仅可以判断数组中是否有具有特定名称的人,还可以使用O(1)查找整个对象.考虑到这个地图只会按名称索引人,如果你想要另一个标准,你需要另一个地图.同时保持两个数据结构同步并不容易(从数据中删除一个元素也应该从地图中删除等)
总而言之,在我们的示例中,一如既往地提高速度会牺牲其他内容,内存和代码复杂性.
示例:filter,map,reduce等方法遍历数组中的每个项目或对象,
ArrPerson.filter(function(item){
console.log(item)
});
Run Code Online (Sandbox Code Playgroud)
forEach :还遍历数组中的每个项目/对象
ArrPerson.forEach(function(key,value){
console.log(key);
console.log(value)
})
Run Code Online (Sandbox Code Playgroud)
问题说数组很大,所以
native for loop 是比上述任何一种都快的方式,并且缓存的长度可以提高几毫秒(毫秒)。
https://jsperf.com/native-map-versus-array-looping
for(var i = 0, len = ArrPerson.length; i < len; i++){
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15366 次 |
| 最近记录: |