頁面包含一個按鈕和兩個輸入框。用戶在第一個框輸入內容(如 12345),點擊按鈕後,第二個框顯示反轉後的字符串(54321)。
btn.onclick = function() {
input2.value = input1.value.toString().reverse(); // 錯誤!
}
錯誤原因:String.prototype 沒有 reverse() 方法,reverse() 是數組方法。字符串需先轉為數組,反轉後再拼接。
<input type="text" id="input1" placeholder="請輸入內容">
<input type="text" id="input2" readonly>
<button id="btn">反轉</button>
<script>
const input1 = document.getElementById('input1');
const input2 = document.getElementById('input2');
const btn = document.getElementById('btn');
btn.addEventListener('click', () => {
// 展開運算符 + reverse + join
input2.value = [...input1.value].reverse().join('');
// 或使用 Array.from
// input2.value = Array.from(input1.value).reverse().join('');
});
</script>
btn.onclick = function() {
var str = input1.value;
// split('') 轉字符數組 -> reverse() -> join('') 拼回字符串
input2.value = str.split('').reverse().join('');
};
function reverseString(str) {
let result = '';
for (let i = str.length - 1; i >= 0; i--) {
result += str[i];
}
return result;
}
// 使用
btn.onclick = function() {
input2.value = reverseString(input1.value);
};
上述 split('') 和 [...str] 在處理代理對(如 😀)時會將其拆分為兩個無效字符。正確方式:
// 使用 Array.from (正確處理 Unicode 碼點)
input2.value = Array.from(input1.value).reverse().join('');
// 或 正則匹配字素簇 (Grapheme Cluster) - 需第三方庫如 grapheme-splitter
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>字符串反轉演示</title>
<style>
.container { padding: 20px; font-family: sans-serif; }
.row { margin: 10px 0; }
label { width: 80px; display: inline-block; }
input { padding: 5px; width: 300px; }
button { padding: 5px 15px; cursor: pointer; }
</style>
</head>
<body>
<div class="container">
<div class="row">
<label>原始輸入:</label>
<input type="text" id="srcInput" placeholder="輸入任意字符...">
</div>
<div class="row">
<label>反轉結果:</label>
<input type="text" id="destInput" readonly>
</div>
<div class="row">
<button id="revBtn">執行反轉</button>
</div>
</div>
<script>
const src = document.getElementById('srcInput');
const dest = document.getElementById('destInput');
document.getElementById('revBtn').addEventListener('click', () => {
dest.value = Array.from(src.value).reverse().join('');
});
</script>
</body>
</html>