我有一个需要两个列表的函数(两个列表中的每个项目都是相同的类型)。如果第一个列表中不存在第二个列表中的项目,则仅将第二个列表中的项目添加到第一个列表中。为了确定它是否存在于列表中,我比较了属性 pk。
addUniqueItemsToList: function (sourceList, toAddList) {
for (var a = 0; a < toAddList.length; a++) {
var doesItemExist = false;
for (var b = 0; b < sourceList.length; b++) {
if (sourceList[b].pk == toAddList[a].pk) {
doesItemExist = true;
break;
}
}
if (!doesItemExist) {
sourceList.push(toAddList[a]);
}
}
}
在 javascript 中是否有一种方法,可以通过将属性名称传递给函数来将其与对象的其他属性进行比较,而不是比较 pk?即 addUniqueItemsToList: function (sourceList, toAddList, propertyName)
最佳答案
是的,您可以直接通过对象属性进行比较,并使用字符串作为键 ej array['mykey'] 动态访问属性。另外,如果不是在 for (1for - n for) 中执行 for ,而是创建一个映射以避免过多的迭代,那就更好了:
例如:当 items.length = 100 & anotherItems.length = 200 时,没有 map 的迭代次数
100*200 = 20000 次可能的迭代。
例如。使用 items.length = 100 & anotherItems.length = 200 创建 map 的迭代次数
300 次迭代。
我的做法示例:
var items = [{_id: 1, text: "Text 1"}, {_id:2, text: "Text 2"}];
var anotherItems = [{_id: 1, text: "Text 1"}];
var mapByProperty = function(array, prop) {
var map = [];
for (var i = 0, len = array.length; i !== len; i++) {
map[array[i][prop]] = array[i];
}
return map;
};
var commonUniqueProperty = '_id';
var mappedAnotherItemsById = mapByProperty(anotherItems, commonUniqueProperty);
for(var i = 0, len = items.length; i !== len; i++) {
if(mappedAnotherItemsById[items[i][commonUniqueProperty]]) {
console.log(items[i]);
}
}
关于JavaScript。通过字符串访问属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30714881/