首页 文章

JavaScript |创建更改数组中值的间隔

提问于
浏览
0

我有一个数组,一个简化的形式是这样的:

let array = [
  {id: 1, value: 0}, 
  {id: 2, value: 0}, 
  {id: 3, value: 0}
];

现在我想创建一个间隔,它每秒增加id为3的对象上的值 . 我现在要做的是用 array[2].value 定位对象 . 只要数组没有改变,这就可以工作 .

我使用的数组不断变化,这意味着元素以异步方式被删除/添加 . 当发生这种情况时,间隔指向错误的元素 . 如果我要删除示例中的元素[1],则间隔现在指向未定义的元素([2]) .

我正在考虑使用关联数组(id作为索引),但在Angular中,当我这样做时,ngFor不再可靠地工作 . 由于同样的原因,对象也无法正常工作 .

即使索引发生更改,如何创建更改数组元素属性的间隔?或者我的问题有更好的解决方案吗?

2 回答

  • 1

    使用find方法:

    function updateValue () {
       var item = array.find(item => item.id === 3)
       if (item) item.value++
    }
    
    setTimeout(updateValue, 1000)
    
  • 1

    您应该持有对象的引用,而不是每次都使用索引 . 例如:

    let array = [
      {id: 1, value: 0}, 
      {id: 2, value: 0}, 
      {id: 3, value: 0}
    ];
    
    function startIncrementing(elem) {
      setInterval(() => elem.value += 5, 500);
    }
    
    // Log the array every second
    setInterval(() => console.log(array), 1000);
    
    // Start the increment interval
    startIncrementing(array[2]);
    
    // Remove an elemnt after 1 second
    setTimeout(() => array.splice(1, 1), 1000);
    

相关问题