【问题标题】:Trying to increment an integer in an Array尝试增加数组中的整数
【发布时间】:2021-07-06 11:29:13
【问题描述】:

晚上好, 每次调用我的函数时,我都试图增加一个整数,我的数组中的索引位置为“0”。我用 .push 添加了变量,但我只想添加一个。我正在尝试使用 indexof(),我也尝试过 findIndex()。下面是我的代码

  const addFunction = async () => {
    var storage_array = await AsyncStorage.getItem(ASYNC_STORAGE_KEY);
     try {
       if(storage_array) {
         storage_array = JSON.parse(storage_array);
         let flow_complete = 0;
     

 
         var foundIndex = storage_array.indexOf(flow_complete);
         console.log(foundIndex);
         storage_array[foundIndex] = flow_complete++;

        await AsyncStorage.setItem(ASYNC_STORAGE_KEY, JSON.stringify(storage_array));
         console.log('THIS IS THE ASYNCSTORAGE', storage_array);

       } else {
        flow_complete = 0;
        console.log('Storage array is empty')
       }
     } catch (error) {
       console.log(error);
     }
  }

【问题讨论】:

  • 需要澄清一下。调用函数时,您希望存储数组的第一个元素递增吗?您现在似乎正在做的是寻找flow_complete(始终为零)的值具有的任何索引,并将其设置为flow_complete++,这将始终为一。我想这不是你打算做的。
  • 另外,您能否提供一个您希望storage_array 看起来像的样本?
  • theJuls 这是正确的,这不是我想要做的。数组看起来像 [0, "show_flow_explanation"],我想在每次调用函数时递增数字 0。
  • 将 storage_array.splice(storage_array.indexOf(flow_complete), 0, flow_complete++);工作吗?
  • 我不知道,我不完全理解您要做什么。绝对需要重新定义您在该代码块中的目标。另外,不要忘记更新您的帖子,使用您期望 storage_array 在这一点上的样子。

标签: javascript arrays reactjs react-native asynchronous


【解决方案1】:

在用您的评论重新措辞后:

[...] 目标是获取数组第 0 位的数字“0”,并在每次函数运行时将其递增 1

我看到的第一个问题是您可能误用了indexOf 函数。这不会给你一个数组的索引,而是一个数组的特定值的位置。

例子:

const arr = [9, 2, 7, 14]
const index = arr.indexOf(9) // This will be 0, because the index of the number 9 in this array is 0 
const otherIndex = arr.indexOf(7) // This will be 2, because the index of the number 7 in this array is 2

因此,要访问第 0 位的元素,您需要执行 arr[0]。因此,在您的代码中,您需要执行以下操作:

storage_array = JSON.parse(storage_array);
let flow_complete = 0;
     
// notice there is no need to get the `indexOf` 0 since you do want the position 0 
storage_array[0] = flow_complete++;

现在...这将有第二个问题,即您对增量运算符++ 的使用。尽管这会增加 flow_complete 变量,但它不会返回它以设置 storage_array[0],因为您打算这样做。

要解决此问题,您只需在将 flow_complete 分配给 storage_array[0] 之前将其递增。它看起来像这样:

let flow_complete = 0;

flow_complete++;
storage_array[0] = flow_complete

但是,如果我对您上述评论的解释是正确的,那么还有一个问题,即您在每次函数运行时将flow_complete 分配给storage_array[0]flow_complete 设置为 0,正如您在 addFunction 范围内的代码块中看到的那样,这意味着它每次运行时都会返回到 0

回到你原来的评论,你想增加 storage_array 的第 0 个索引中的值,而不是 flow_complete 本身,对吗? 如果是这种情况,您可以完全摆脱flow_complete 变量,而是增加storage_array[0]。这将使您的 if 块如下所示:

 if(storage_array) {
         storage_array = JSON.parse(storage_array);
     
         storage_array[0]++;

        await AsyncStorage.setItem(ASYNC_STORAGE_KEY, JSON.stringify(storage_array));
         console.log('THIS IS THE ASYNCSTORAGE', storage_array);

       }

【讨论】:

  • 感谢朱尔斯提供了非常丰富的答案
  • 很高兴为您提供帮助! :) 如果您有任何进一步的问题,将根据需要进行调整。
猜你喜欢
  • 1970-01-01
  • 2018-11-24
  • 2023-03-24
  • 2021-03-11
  • 1970-01-01
  • 2017-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多