我有一种情况,我有 3 个不同的数组,其中的对象数量非常不同。我已经阅读了很多关于此的问题和博客文章,但我仍然不确定何时使用什么。
PS!我最大的问题是我需要迭代和推送(非常适合数组),还要查找数组中是否存在并删除(更适合对象)。 不需要特定顺序。
我不允许在 array1
和 array1clicked
中使用相同的对象
因为他们应该执行不同的操作。
在我的示例中什么时候最好使用对象什么时候使用数组?我应该用对象替换什么,什么应该保留为数组?我很确定其中的对象数量也很重要,对吧?
我当前的代码:
//Objects in arrays are literally custom {objects} with custom prototypes and html
var array1 = [ 20 objects ];
var array1clicked = [];
var array2 = [ 250 objects ];
var array2clicked = [];
var array3 = [ 50 000 objects ];
var array3clicked = [];
//Each object in arrays has event attached
objecthtml.click(function() {
//Add to clicked array
array1clicked.push(thisobject);
//Remove from initial array
var index = array1.indexOf(thisobject);
if (index > -1) {
array1.splice(index, 1);
}
}
//Same with array2 and array3 objects
//Iterations on different conditions
var array1count = array1.length;
var array1clickedcount = array1clicked.length;
//Same with array2 and array3
if(condition1) {
for(a = 0; a < array1count; a++) {
array1[a].div.style.visibility = 'hidden';
}
//Same with array2 and array3 objects
for(a = 0; a < array1clickedcount; a++) {
array1clicked[a].div.style.visibility = 'visible';
}
//Same with array2clicked and array3clicked objects
}
else if(condition2) {
for(a = 0; a < array1count; a++) {
array1[a].div.style.visibility = 'visible';
}
//Same with array2 and array3 objects
for(a = 0; a < array1clickedcount; a++) {
array1clicked[a].div.style.visibility = 'hidden';
}
//Same with array2clicked and array3clicked objects
}
最佳答案
看起来你想要一个包含这些操作的数据结构:
- 迭代
- 插入
- 删除
- 搜索
对于数组,问题是搜索和删除(重新索引)很慢。
对于对象,问题是属性名称只能是字符串。
完美的结构是一个集合。
var s = new Set();
s.add(123); // insert
s.has(123); // search
s.delete(123); // delete
s.values(); // iterator
关于javascript - 什么时候用对象,什么时候用数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35003432/