如何从source、destination和prices数组中获取指定路线的价格?
解决方案:匹配出发地与目的地获取对应价格
嘿,这事儿其实挺简单的,咱们只需要遍历数组,找到**出发地等于src且目的地等于des**的索引位置,然后取出对应prices数组里的值就行。下面给你几种常用的实现方式,都是JavaScript的写法:
方法一:普通for循环(最直观)
这种方式适合新手理解,逐一遍历每个索引,匹配条件后就拿到目标价格:
const source = ["hyderabd","banglore","hyderabad","chennai","pune","mumbai"]; const destination = ["pune","chennai","mumbai","hyderabad","banglore","hyderabad"]; const prices = ["500","300","400","600","500","500"]; const src = "hyderabad"; const des = "mumbai"; let targetPrice = null; // 遍历数组每个元素的索引 for (let i = 0; i < source.length; i++) { // 同时匹配出发地和目的地 if (source[i] === src && destination[i] === des) { targetPrice = prices[i]; break; // 找到第一个匹配项就停止遍历,提升效率 } } console.log(targetPrice); // 输出:"400"
方法二:使用数组findIndex方法(更简洁)
利用findIndex直接找到符合条件的索引,再通过索引取价格:
const source = ["hyderabd","banglore","hyderabad","chennai","pune","mumbai"]; const destination = ["pune","chennai","mumbai","hyderabad","banglore","hyderabad"]; const prices = ["500","300","400","600","500","500"]; const src = "hyderabad"; const des = "mumbai"; // 找到符合条件的索引 const matchIndex = source.findIndex((city, index) => city === src && destination[index] === des ); // 通过索引获取对应价格 const targetPrice = prices[matchIndex]; console.log(targetPrice); // 输出:"400"
方法三:使用forEach遍历
通过forEach遍历每个元素,匹配条件后记录价格:
const source = ["hyderabd","banglore","hyderabad","chennai","pune","mumbai"]; const destination = ["pune","chennai","mumbai","hyderabad","banglore","hyderabad"]; const prices = ["500","300","400","600","500","500"]; const src = "hyderabad"; const des = "mumbai"; let targetPrice = null; source.forEach((city, index) => { if (city === src && destination[index] === des) { targetPrice = prices[index]; } }); console.log(targetPrice); // 输出:"400"
小提示:
注意看你source数组里的第一个元素是"hyderabd"(少了一个字母a),和你的src值"hyderabad"不匹配,所以不会被选中;第三个元素才是正确拼写的"hyderabad",刚好对应目的地"mumbai"和价格"400",所以能准确拿到结果。
内容的提问来源于stack exchange,提问作者swetha
相关产品推荐
相关产品推荐

