溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何使用JavaScript數組對象寫法來計算起始車站車費問題

發布時間:2021-09-30 11:09:52 來源:億速云 閱讀:154 作者:柒染 欄目:云計算
# 如何使用JavaScript數組對象寫法來計算起始車站車費問題

## 引言

在地鐵或公交計費系統中,常需要根據乘客的起始站和終點站計算車費。本文將介紹如何利用JavaScript數組對象的特性,構建一個高效的車費計算系統。通過數組方法(如`findIndex`、`slice`)和對象存儲站點信息,我們可以實現清晰、可維護的解決方案。

---

## 一、問題場景分析

假設某地鐵線路共有10個車站,票價規則如下:
- 0-3站:3元
- 4-6站:4元
- 7站及以上:5元

需要實現一個函數,輸入起始站名和終點站名,返回對應車費。

---

## 二、數據結構設計

### 1. 使用對象數組存儲站點信息
```javascript
const stations = [
  { id: 1, name: "車站A" },
  { id: 2, name: "車站B" },
  // ...其他車站
  { id: 10, name: "車站J" }
];

2. 票價規則映射

const fareRules = [
  { maxStations: 3, fare: 3 },
  { maxStations: 6, fare: 4 },
  { maxStations: Infinity, fare: 5 }
];

三、核心算法實現

1. 查找站點索引

使用findIndex方法定位車站位置:

function getStationIndex(stationName) {
  return stations.findIndex(station => 
    station.name === stationName
  );
}

2. 計算經過站數

通過索引差值計算實際經過的站數(需取絕對值):

const startIdx = getStationIndex("車站A");
const endIdx = getStationIndex("車站D");
const stationCount = Math.abs(endIdx - startIdx) + 1; // 包含兩端

3. 匹配票價規則

使用find方法匹配對應的票價檔位:

function calculateFare(stationsPassed) {
  const rule = fareRules.find(rule => 
    stationsPassed <= rule.maxStations
  );
  return rule.fare;
}

四、完整代碼示例

const metroSystem = {
  stations: [
    { id: 1, name: "車站A" },
    { id: 2, name: "車站B" },
    // ...其他8個車站
  ],
  
  fareRules: [
    { maxStations: 3, fare: 3 },
    { maxStations: 6, fare: 4 },
    { maxStations: Infinity, fare: 5 }
  ],
  
  getFare(startStation, endStation) {
    const startIdx = this.stations.findIndex(s => s.name === startStation);
    const endIdx = this.stations.findIndex(s => s.name === endStation);
    
    if (startIdx === -1 || endIdx === -1) {
      throw new Error("無效的車站名稱");
    }
    
    const stationsPassed = Math.abs(endIdx - startIdx) + 1;
    const matchedRule = this.fareRules.find(r => stationsPassed <= r.maxStations);
    
    return matchedRule.fare;
  }
};

// 使用示例
console.log(metroSystem.getFare("車站A", "車站C")); // 輸出3
console.log(metroSystem.getFare("車站A", "車站E")); // 輸出4

五、優化與擴展

1. 異常處理

  • 添加對無效車站名的校驗
  • 處理起始站等于終點站的情況

2. 動態票價規則

可將票價規則改為函數形式,支持更復雜的計算邏輯:

{
  getFare: (stationsPassed) => 
    stationsPassed <= 3 ? 3 : 
    stationsPassed <= 6 ? 4 : 5
}

3. 多線路支持

擴展數據結構為二維數組,添加lineId屬性:

const network = [
  {
    line: "1號線",
    stations: [...],
    fareRules: [...]
  },
  // ...其他線路
]

六、總結

通過JavaScript數組對象: 1. 使用findIndex快速定位元素位置 2. 通過對象數組實現結構化數據存儲 3. 利用find方法實現規則匹配 4. 代碼可讀性強且易于擴展

這種方法不僅適用于交通計費系統,也可應用于其他需要區間計算的場景(如快遞運費、階梯電價等)。 “`

(注:實際字數為約750字,可通過擴展”優化與擴展”章節或增加具體案例補充至850字)

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女