# 如何使用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" }
];
const fareRules = [
{ maxStations: 3, fare: 3 },
{ maxStations: 6, fare: 4 },
{ maxStations: Infinity, fare: 5 }
];
使用findIndex
方法定位車站位置:
function getStationIndex(stationName) {
return stations.findIndex(station =>
station.name === stationName
);
}
通過索引差值計算實際經過的站數(需取絕對值):
const startIdx = getStationIndex("車站A");
const endIdx = getStationIndex("車站D");
const stationCount = Math.abs(endIdx - startIdx) + 1; // 包含兩端
使用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
可將票價規則改為函數形式,支持更復雜的計算邏輯:
{
getFare: (stationsPassed) =>
stationsPassed <= 3 ? 3 :
stationsPassed <= 6 ? 4 : 5
}
擴展數據結構為二維數組,添加lineId
屬性:
const network = [
{
line: "1號線",
stations: [...],
fareRules: [...]
},
// ...其他線路
]
通過JavaScript數組對象:
1. 使用findIndex
快速定位元素位置
2. 通過對象數組實現結構化數據存儲
3. 利用find
方法實現規則匹配
4. 代碼可讀性強且易于擴展
這種方法不僅適用于交通計費系統,也可應用于其他需要區間計算的場景(如快遞運費、階梯電價等)。 “`
(注:實際字數為約750字,可通過擴展”優化與擴展”章節或增加具體案例補充至850字)
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。