可以使用HTML文本区域的输入来填充堆栈或数组。以下是一个简单的示例,展示了如何将HTML文本区域的输入分割成数组,并将其元素逐个压入堆栈中。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Text Area to Stack/Array</title>
</head>
<body>
<textarea id="inputArea" rows="4" cols="50" placeholder="Enter items separated by commas"></textarea>
<button onclick="processInput()">Process Input</button>
<div id="output"></div>
<script src="script.js"></script>
</body>
</html>
function processInput() {
const inputArea = document.getElementById('inputArea');
const inputValue = inputArea.value;
const itemsArray = inputValue.split(',').map(item => item.trim()); // Split by comma and trim whitespace
const stack = [];
for (const item of itemsArray) {
stack.push(item);
}
displayResult(stack);
}
function displayResult(stack) {
const outputDiv = document.getElementById('output');
outputDiv.innerHTML = `<p>Stack contents:</p><ul>${stack.map(item => `<li>${item}</li>`).join('')}</ul>`;
}
<textarea>
元素用于用户输入。processInput
函数。<div>
元素来显示处理后的结果。processInput
函数获取文本区域的值,并使用split(',')
方法将其分割成一个数组。每个元素通过map
方法去除前后空白。stack
,并使用for...of
循环将处理后的每个元素压入堆栈。displayResult
函数用于在页面上显示堆栈的内容。通过这种方式,可以有效地将HTML文本区域的输入转换为数组,并利用堆栈数据结构进行进一步操作。
领取专属 10元无门槛券
手把手带您无忧上云