javascript - 如何获取稀疏数组中的下一个元素

标签 javascript arrays

我知道 JavaScript 中的数组与传统数组的不同之处在于它们只是底层对象。因此,在内存管理方面,JavaScript 允许稀疏数组以类似于密集数组的方式运行。使用稀疏数组时,有没有办法有效地到达该数组中的下一个元素?

例如,给定这个数组:

var foo = [];
foo[0] = '0';
foo[1] = '1';
foo[2] = '2';
foo[100] = '100';

console.log(foo.length); // => 101

我知道有一种方法可以通过使用 for ... in 来获取所有 元素,如下所示:

for (var n in foo){
    console.log(n);
}
// Output: 
// 0
// 1
// 2
// 100

但是,是否有一种明确的方法可以简单地从这些元素中的一个转到下一个?

例如,是否存在某种方法可以实现与此类似的行为?

var curElement = foo[2]; // => 2 (the contents of foo[2])
var nextElement = curElement.next(); // => 100 (the contents of foo[100])
//                           ^^^^^^
// Not an actual function, but does there exist some way to potentially
// mimic this type of behavior efficiently?

最佳答案

您可以创建自己的 SparseArray 类型,它具有所有 Array 方法,但维护一个单独的索引列表以进行迭代,以便您可以有效地跳过漏洞。

这是这种类型的开始。它允许您迭代、推送、添加特定索引、获取/检查特定索引。

我还添加了一个 .toString() 用于显示。

未完全测试,因此可能存在错误。您需要根据需要添加功能。

function SparseArray(arr) {
  this.data = arr || [];
  this.indices = [];

  for (var i = 0; i < this.data.length; i++) {
    if (this.data.hasOwnProperty(i)) {
      this.indices.push(i);        
    }
  }
}

SparseArray.prototype.forEach = function(cb, thisArg) {
  for (var i = 0; i < this.indices.length; i++) {
    cb.call(thisArg, this.data[this.indices[i]], i, this);
  }
};

SparseArray.prototype.push = function(item) {
  this.indices.push(this.data.push(item) - 1);
};

SparseArray.prototype.addAt = function(idx, item) {
  if (idx >= this.data.length) {
    this.indices.push(idx);
    
  } else if (!(idx in this.data)) {
    for (var i = 0; i < this.indices.length; i++) {
      if (this.indices[i] >= idx) {
        this.indices.splice(i, 0, idx);
        break;
      }
    }
  }
  this.data[idx] = item;
};

SparseArray.prototype.hasIndex = function(idx) {
  return idx in this.data;
};

SparseArray.prototype.getIndex = function(idx) {
  return this.data[idx];
};

SparseArray.prototype.nextFrom = function(idx) {
  for (var i = 0; i < this.indices.length; i++) {
    if (this.indices[i] >= idx) {
      return this.data[this.indices[i]];
    }
  }
};

SparseArray.prototype.toString = function() {
  var res = [];
  this.forEach(function(item) {
    res.push(item);
  });
  return res.join(", ");
};

var foo = [];
foo[0] = '0';
foo[1] = '1';
foo[2] = '2';
foo[100] = '100';

var pre = document.querySelector("pre");

var sa = new SparseArray(foo);

pre.textContent += "Start\n" + sa + "\n\n";

sa.addAt(1000, "1000");

pre.textContent += "Adding 1000\n" + sa + "\n\n";

sa.push("1001");

pre.textContent += "Pushing 1001\n" + sa + "\n\n";

pre.textContent += "Next from 300 is: " + sa.nextFrom(300) + "\n\n";
<pre></pre>

关于javascript - 如何获取稀疏数组中的下一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34572862/

相关文章:

javascript - 如何使 requirejs shimmed 模块能够访问未定义的依赖项

javascript - React Router - 一起使用 MemoryRouter 和 Router 进行路由(有些链接使用内存,而其他链接则更改 url)

arrays - 如何使用 Firebase 数据库进行分页?

Javascript 将数组项与其他数组中的每个项组合为文本

python - 扩展 numpy 掩码

javascript - 我可以将 map 函数与 2 个数组一起使用吗?

javascript - 尝试将 react-select 导入使用 create-react-app 创建的项目时出错

javascript - 使用 css 关闭 javascript?

javascript - jQuery 移动响应面板滑动打开/关闭关闭

javascript - javascript 函数无法生成精确的更改