如何获取下一个值(在,值之后)



我有这样的数据=

Hi,I,Am,Here,to,BP,23,HP,34,COST,45

我想为惠普和成本获得BP的价值,那么我如何才能获得下一个价值。

解释


const array = [BP,HP,COST]
const string = ["HI","I","AM","BP","20","HP","35","COST","30"]
expected output = Value of BP is 20, Value of HP is 35, Value of COST is 30

假设你知道BP、HP和COST的键(我没有误解你的问题(,你只需要+1索引。

var data = ["Hi", "I", "Am", "Here", "to", "BP", 23, "HP", 34, "COST", 45];
var indexBP = data.indexOf("BP");
var BP = data[indexBP + 1]; // BP = 23

const array = ['BP','HP','COST']
const string = ["HI","I","AM","BP","20","HP","35","COST","30"]
let output = "";
array.forEach(x => {
output += `Value of ${x} is ${string[string.indexOf(x) + 1]} `
})
console.log(output)

您可以有一个简单的循环,并与indexOf + 1组合以获得您想要的值,假设位置是可预测的

您可以尝试获取该键的索引。例如:从您的数组中,BP的索引为5,下一个值(23(的索引为6

从这个例子中,我们可以得到这个逻辑(array是变量的名称(

const array = ["BP","HP","COST"]
const string = ["HI","I","AM","BP","20","HP","35","COST","30"]
const newArray = []
for (const key of array) {
newArray.push(string[string.indexOf(key) + 1])
}

这可能是获得Expected Output的一种可能的实现方式。

const strArr = ["HI", "I", "AM", "BP", "20", "HP", "35", "COST", "30"];
console.log(
['BP', 'HP', 'COST']
.map(
k => `Value of ${k} is ${strArr[strArr.indexOf(k) + 1]}`
).join(', ')
);

只加1索引

const array = ['BP', 'HP', 'COST'];
const string = ["HI","I","AM","BP","20","HP","35","COST","30"];
let output = array.map(
k => `Value of ${k} is ${string[string.indexOf(k) + 1]}`
).join(', ');
output += '.';
console.log(output);

最新更新