晚上好,每次我的函数被调用时,我都试图增加一个整数,该整数在我的数组中的索引位置为“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);
}
}
在用您的评论重新表述问题之后:
[...] 目标是获取数组第 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
每次运行时都会返回。
回到你原来的评论,你想增加第 0 个索引中的值storage_array
,而不是flow_complete
它本身,对吗?如果是这种情况,您可以完全摆脱flow_complete
变量并改为 increment storage_array[0]
。这将使您的 if-block 如下所示:
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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句