new js实现
JavaScript 实现新功能的方法
使用现代 JavaScript(ES6+)可以实现高效、简洁的代码。以下是一些常见功能的实现方式:
箭头函数
const add = (a, b) => a + b;
类定义
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, ${this.name}`);
}
}
模板字符串
const user = 'Alice';
console.log(`Welcome ${user}!`);
解构赋值
const [first, second] = [1, 2];
const {name, age} = {name: 'Bob', age: 30};
异步处理方案
Promise 使用
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
async/await
async function getData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
模块化开发
导出模块
// math.js
export const PI = 3.14159;
export function square(x) {
return x * x;
}
导入模块
import { PI, square } from './math.js';
console.log(square(PI));
常用数组方法
map/filter/reduce
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(x => x * 2);
const evens = numbers.filter(x => x % 2 === 0);
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
对象处理
扩展运算符
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };
可选链
const user = { profile: { name: 'Alice' } };
console.log(user?.profile?.name);
错误处理
try/catch
try {
// 可能出错的代码
} catch (error) {
console.error('发生错误:', error.message);
}
浏览器 API 使用
LocalStorage
localStorage.setItem('key', 'value');
const data = localStorage.getItem('key');
Geolocation
navigator.geolocation.getCurrentPosition(
position => console.log(position.coords),
error => console.error(error)
);






