表單輸入、標籤管理、ID 清單去重:使用者輸入「1,2,2,3,4,4,5,6」需自動轉為「1,2,3,4,5,6」。
function uniqueIds(str, separator = ',') {
return [...new Set(str.split(separator).map(s => s.trim()))].join(separator);
}
// 使用
const input = '1,2,2,3,4,4,5,6';
console.log(uniqueIds(input)); // "1,2,3,4,5,6"
// 保持原順序 (Set 保持插入順序,ES2015 規範)
const input2 = '3,1,2,1,3';
console.log(uniqueIds(input2)); // "3,1,2"
function uniqueIdsLegacy(str, separator = ',') {
const seen = Object.create(null); // 無原型鏈,純雜湊表
const result = [];
str.split(separator).forEach(item => {
const trimmed = item.trim();
if (trimmed && !seen[trimmed]) {
seen[trimmed] = true;
result.push(trimmed);
}
});
return result.join(separator);
}
/**
* 陣列去重:保持順序、支援任意類型 (以 JSON.stringify 比較物件)
*/
function uniqueArray(arr) {
const seen = new Set();
return arr.filter(item => {
const key = typeof item === 'object' ? JSON.stringify(item) : item;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
/**
* 字串 ID 去重:支援中文逗號、空格混雜
*/
function dedupeIdString(str) {
if (!str) return '';
// 統一分隔符:中文逗號、空格 → 英文逗號
const normalized = str.replace(/[,\s]+/g, ',');
// 分割、去空、去重、重組
return uniqueArray(normalized.split(',').filter(Boolean)).join(',');
}
// 表單整合範例
function bindIdDedupe(inputSelector) {
document.querySelectorAll(inputSelector).forEach(input => {
input.addEventListener('blur', function() {
this.value = dedupeIdString(this.value);
});
});
}
// 使用:所有 class="id-input" 的輸入框自動去重
bindIdDedupe('.id-input');
| 方法 | 時間 (ms) | 記憶體 | 相容性 |
|---|---|---|---|
| Set + spread | ~12 | 低 | ES6+ |
| Object.create(null) + filter | ~8 | 低 | IE11+ |
| 雙層迴圈 (O(n²)) | ~4500 | 高 | 全 |
| indexOf 檢查 (O(n²)) | ~3800 | 高 | 全 |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ID 去重表單 Demo</title>
<style>
.field { margin: 10px 0; }
label { display: block; margin-bottom: 4px; font-weight: bold; }
textarea, input { width: 100%; max-width: 500px; padding: 8px; font-family: monospace; }
.hint { color: #666; font-size: 12px; margin-top: 4px; }
</style>
</head>
<body>
<div class="field">
<label>單行輸入 (離開自動去重)</label>
<input type="text" class="id-input" value="1,2,2,3,4,4,5,6">
<div class="hint">支援:英文逗號、中文逗號、空格混用</div>
</div>
<div class="field">
<label>多行文字域 (離開自動去重)</label>
<textarea class="id-input" rows="3">1,2,3,4,5,6,4,5,6</textarea>
</div>
<script>
// 核心去重函式 (ES6 Set 版)
function dedupe(str) {
return [...new Set(str.split(/[,,\s]+/).filter(Boolean))].join(',');
}
// 綁定所有 .id-input
document.querySelectorAll('.id-input').forEach(el => {
el.addEventListener('blur', function() {
const original = this.value;
const cleaned = dedupe(original);
if (cleaned !== original) {
this.value = cleaned;
// 可選:視覺提示
this.style.background = '#fffde7';
setTimeout(() => this.style.background = '', 1000);
}
});
});
</script>
</body>
</html>
/[,,\s]+/
// 解析:
// [ , , \s ] 字元集合:英文逗號、中文逗號、所有空白字元(空格/Tab/換行)
// + 一個或多個連續
// 等效於:split 時自動合併多個分隔符,並過濾空字串
現代專案首選 Set + 正則分割:程式碼最少、效能最好、語義最清晰。舊環境用 Object.create(null) 雜湊表。核心三步驟:**正規化分隔符 → 分割過濾 → 去重重組**。封裝為通用工具函式並綁定 blur 事件,即可滿足表單自動去重需求。