我定义了一个对象
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"));
现在我需要一种有效的机制来识别 ArrPerson 对象数组是否包含特定名称?
我知道我们可以使用 for 循环和检查遍历数组。假设数组很大,还有其他有效的方法吗?
最佳答案
您可以使用数组过滤器或查找方法
ArrPerson.find(p=>p.name=='john')
ArrPerson.filter(p=>p.name=='john')
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);
这个 ES6 Map 将根据它包含的名称保留整个数组的索引。如果你想看看你的数组是否包含一个名字,你可以这样做:
hashmap.has('john')//true
这种方法的复杂度为 O(1)。它只会在 map 上检查一次,以查看该名称是否存在于您的数组中。此外,您可以跟踪 map 内的数组索引:
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 ...
通过这种方法,您不仅可以判断数组中是否存在具有特定名称的人,还可以用 O(1) 的复杂度找到整个对象。 请注意,如果您需要其他标准,您需要另一张 map ,此 map 只会按姓名索引人员。保持两个数据结构同步也不容易(从数组中删除一个元素也应该从 map 中删除,等等)
总而言之,在我们的示例中,速度的提高总是以牺牲其他东西、内存和代码复杂性为代价。
关于javascript - 在 javascript/node.js 中迭代对象数组的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35084308/