<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>移除数组中的指定元素</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
line-height: 1.6;
}
.container {
background-color: #f5f5f5;
padding: 20px;
border-radius: 5px;
margin-bottom: 20px;
}
button {
background-color: #4CAF50;
color: white;
padding: 10px 15px;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
pre {
background-color: #f0f0f0;
padding: 10px;
border-radius: 4px;
overflow-x: auto;
}
</style>
</head>
<body>
<h1>从数组中移除指定元素</h1>
<div class="container">
<h2>示例演示</h2>
<p>原始数组: <span id="originalArray"></span></p>
<p>要移除的元素: <input type="text" id="elementToRemove" value="apple"></p>
<button onclick="removeElementDemo()">移除元素</button>
<p>结果数组: <span id="resultArray"></span></p>
</div>
<div class="container">
<h2>实现代码</h2>
<p>以下是从数组中移除指定元素的JavaScript实现代码:</p>
<pre><code>
function removeElementFromArray(arr, element) {
// 方法1: 使用filter方法
// return arr.filter(item => item !== element);
// 方法2: 使用splice方法
for (let i = arr.length - 1; i >= 0; i--) {
if (arr[i] === element) {
arr.splice(i, 1);
}
}
return arr;
}
function removeElementDemo() {
const originalArray = ['apple', 'banana', 'orange', 'apple', 'grape'];
const elementToRemove = document.getElementById('elementToRemove').value;
const resultArray = removeElementFromArray([...originalArray], elementToRemove);
document.getElementById('originalArray').textContent = JSON.stringify(originalArray);
document.getElementById('resultArray').textContent = JSON.stringify(resultArray);
}
// 初始化显示
window.onload = function() {
removeElementDemo();
};
</code></pre>
</div>
<script>
function removeElementFromArray(arr, element) {
// 方法1: 使用filter方法
// return arr.filter(item => item !== element);
// 方法2: 使用splice方法
for (let i = arr.length - 1; i >= 0; i--) {
if (arr[i] === element) {
arr.splice(i, 1);
}
}
return arr;
}
function removeElementDemo() {
const originalArray = ['apple', 'banana', 'orange', 'apple', 'grape'];
const elementToRemove = document.getElementById('elementToRemove').value;
const resultArray = removeElementFromArray([...originalArray], elementToRemove);
document.getElementById('originalArray').textContent = JSON.stringify(originalArray);
document.getElementById('resultArray').textContent = JSON.stringify(resultArray);
}
// 初始化显示
window.onload = function() {
removeElementDemo();
};
</script>
</body>
</html>
262

被折叠的 条评论
为什么被折叠?



