js实现添加


使用 JavaScript 实现添加功能
在 JavaScript 中实现添加功能通常涉及操作 DOM 元素或向数组、对象等数据结构中添加数据。以下是几种常见的实现方式:
向数组添加元素
const array = [1, 2, 3];
array.push(4); // 在数组末尾添加元素
console.log(array); // [1, 2, 3, 4]
array.unshift(0); // 在数组开头添加元素
console.log(array); // [0, 1, 2, 3, 4]
向对象添加属性
const obj = { name: 'Alice' };
obj.age = 25; // 添加新属性
console.log(obj); // { name: 'Alice', age: 25 }
向 DOM 添加元素
const parent = document.getElementById('parent');
const newElement = document.createElement('div');
newElement.textContent = 'New element';
parent.appendChild(newElement); // 添加到父元素的末尾
使用展开运算符添加元素
const originalArray = [1, 2, 3];
const newArray = [...originalArray, 4]; // 添加元素到新数组
console.log(newArray); // [1, 2, 3, 4]
向 Set 添加元素
const set = new Set([1, 2, 3]);
set.add(4); // 添加新元素
console.log(set); // Set {1, 2, 3, 4}
向 Map 添加键值对
const map = new Map([['name', 'Alice']]);
map.set('age', 25); // 添加新键值对
console.log(map.get('age')); // 25
动态添加事件监听器
const button = document.getElementById('myButton');
button.addEventListener('click', function() {
console.log('Button clicked');
});
使用 insertAdjacentHTML 添加 HTML
const container = document.getElementById('container');
container.insertAdjacentHTML('beforeend', '<p>New paragraph</p>');
向表单添加字段
const form = document.getElementById('myForm');
const newInput = document.createElement('input');
newInput.type = 'text';
newInput.name = 'username';
form.appendChild(newInput);
使用类操作添加 CSS 类
const element = document.getElementById('myElement');
element.classList.add('new-class');
这些方法涵盖了 JavaScript 中常见的添加操作场景,可以根据具体需求选择合适的方式实现添加功能。






