【发布时间】: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