我需要调用一个带有特定参数的api。
请看下面的例子:
const apiFunc = (someId, anotherId) => apiCall(someId, anotherId) }
但是在一个名为someArr
的数组中我得到了[1, 'someId', 2, 'anotherId', 3, 'anotherId', 4, 'someId']
我需要在apiCall()
中使用,例如1
(与4
相同),如果'someId'
在旁边,如果'anotherId'
在旁边,2
(与3
相同)。
我怎样才能正确地格式化这个请达到预期的结果?
感谢我试过使用.includes()
,但没有太大的成功。
您可以使用filter
来提取"someId"前面的所有值,并使用另一个filter
调用来提取"anotherId"前面的所有值。然后在调用api时对它们进行配对:
// Mock
const apiCall = (someId, anotherId) => console.log(someId, anotherId);
const arr = [1, 'someId', 2, 'anotherId', 3, 'anotherId', 4, 'someId'];
// Extract the "someId" values
const someId = arr.filter((val, i) => arr[i+1] == "someId");
// Extract the "otherId" values
const otherId = arr.filter((val, i) => arr[i+1] == "anotherId");
// Iterate the pairs of someId, otherId:
for (let i = 0; i < someId.length; i++) {
apiCall(someId[i], otherId[i]);
}
可以创建这样一个简单的函数:
const getId = (array, number): string | null => {
const index = array.indexOf(number);
if (index === -1 || index === array.length - 1) {
return null;
}
return array[index + 1];
};
,然后这样使用:
const id1 = getId(someArr, 1); // 'someId'
const id2 = getId(someArr, 3); // 'anotherId'
apiCall(id1, id2);