12×12 表格,每個 <td> 的 id 格式為 "行-列",如 "0-9"、"10-12"。點擊單元格傳入 id,需解析出行號和列號。
function parseCoord(idStr) {
// 以連字符分割,自動處理一位數和兩位數
const parts = idStr.split('-');
if (parts.length === 2) {
const row = parseInt(parts[0], 10);
const col = parseInt(parts[1], 10);
return { row, col };
}
throw new Error('Invalid id format: ' + idStr);
}
// 使用示例
const id = '10-12'; // 或 '0-9'
const { row, col } = parseCoord(id);
console.log(`Row: ${row}, Col: ${col}`); // Row: 10, Col: 12
split('-') 語義清晰,代碼極短,自動適配位數變化。"10-12" 中連字符位置是 2 而非 1)。const COORD_REGEX = /^(\d+)-(\d+)$/;
function parseCoordSafe(idStr) {
const match = idStr.match(COORD_REGEX);
if (match) {
return { row: +match[1], col: +match[2] };
}
return null; // 或拋出異常
}
正則捕獲組同時實現驗證和提取,更健壯。