js原生实现
原生JavaScript实现常见功能
事件监听
使用addEventListener绑定事件:
document.getElementById('myButton').addEventListener('click', function() {
console.log('Button clicked');
});
AJAX请求
使用XMLHttpRequest对象:

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send();
元素选择
通过选择器获取元素:
// 通过ID
const el = document.getElementById('elementId');
// 通过类名
const elements = document.getElementsByClassName('className');
// 通过标签名
const tags = document.getElementsByTagName('div');
// 通过CSS选择器
const firstMatch = document.querySelector('.container');
const allMatches = document.querySelectorAll('.item');
动态创建元素
const newDiv = document.createElement('div');
newDiv.className = 'box';
newDiv.textContent = 'New Element';
document.body.appendChild(newDiv);
类操作
const element = document.getElementById('myElement');
// 添加类
element.classList.add('new-class');
// 移除类
element.classList.remove('old-class');
// 切换类
element.classList.toggle('active');
数据存储
使用localStorage:

// 存储数据
localStorage.setItem('key', 'value');
// 获取数据
const data = localStorage.getItem('key');
// 移除数据
localStorage.removeItem('key');
定时器
// 延时执行
setTimeout(function() {
console.log('Executed after 1 second');
}, 1000);
// 循环执行
const intervalId = setInterval(function() {
console.log('Executed every 1 second');
}, 1000);
// 清除定时器
clearInterval(intervalId);
表单处理
document.forms['myForm'].addEventListener('submit', function(e) {
e.preventDefault();
const formData = new FormData(this);
const username = formData.get('username');
console.log(username);
});
数组操作
常见原生数组方法:
const numbers = [1, 2, 3, 4];
// 遍历
numbers.forEach(function(item) {
console.log(item);
});
// 映射
const doubled = numbers.map(function(item) {
return item * 2;
});
// 过滤
const evens = numbers.filter(function(item) {
return item % 2 === 0;
});
// 查找
const found = numbers.find(function(item) {
return item > 2;
});
对象操作
const person = {
name: 'John',
age: 30
};
// 获取键
const keys = Object.keys(person);
// 获取值
const values = Object.values(person);
// 合并对象
const newPerson = Object.assign({}, person, { city: 'New York' });
字符串操作
const str = 'Hello World';
// 分割
const parts = str.split(' ');
// 替换
const newStr = str.replace('World', 'JavaScript');
// 包含检测
const hasHello = str.includes('Hello');
// 截取
const subStr = str.substring(0, 5);
日期处理
const now = new Date();
// 获取年份
const year = now.getFullYear();
// 获取月份 (0-11)
const month = now.getMonth();
// 获取日期
const day = now.getDate();
// 格式化日期
const formatted = `${year}-${month + 1}-${day}`;
动画实现
使用requestAnimationFrame:
function animate() {
const element = document.getElementById('animated');
let position = 0;
function step() {
position += 1;
element.style.left = position + 'px';
if (position < 100) {
requestAnimationFrame(step);
}
}
requestAnimationFrame(step);
}
Promise实现
function fetchData(url) {
return new Promise(function(resolve, reject) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function() {
if (xhr.status === 200) {
resolve(xhr.response);
} else {
reject(new Error(xhr.statusText));
}
};
xhr.onerror = function() {
reject(new Error('Network Error'));
};
xhr.send();
});
}






