1. eval() 函数
eval()
函数会将传入的字符串作为 JavaScript/TypeScript 代码执行并返回结果。
注意:使用 eval()
存在安全风险,可能导致代码注入攻击,应谨慎使用。
function runEvalDemo(): void {
// 定义变量供 eval 使用
const width: number = 200;
const height: number = 150;
const price: number = 19.99;
const taxRate: number = 0.08;
// 使用 eval 执行表达式
const result1: number = eval("width * height");
const result2: number = eval("price * (1 + taxRate)");
const result3: string = eval("'TypeScript'.toUpperCase()");
// 输出结果
console.log(`表达式 "width * height" 的结果: ${result1}`);
console.log(`表达式 "price * (1 + taxRate)" 的结果: ${result2.toFixed(2)}`);
console.log(`表达式 "'TypeScript'.toUpperCase()" 的结果: ${result3}`);
}
2. data-* 自定义属性
HTML5 允许使用 data-*
前缀创建自定义属性。在 TypeScript 中,可以通过 HTMLElement
的 dataset
属性访问这些属性,属性名会自动转换为驼峰命名。
function runDataAttributeDemo(): void {
const element: HTMLElement | null = document.getElementById('customData');
if (element) {
// 获取自定义属性值
// HTML: <div data-user-id="1001" data-is-active="true">
const userId = element.dataset.userId; // 对应 data-user-id
const role = element.dataset.role; // 对应 data-role
const isActive = element.dataset.isActive; // 对应 data-is-active
console.log(`data-user-id: ${userId}`);
console.log(`data-role: ${role}`);
console.log(`data-is-active: ${isActive}`);
// 修改属性值
element.dataset.isActive = "false";
console.log("修改后的 data-is-active:", element.dataset.isActive);
} else {
console.error('未找到元素 #customData');
}
}
3. forEach() 方法
forEach()
是数组的迭代方法,用于遍历数组元素。它接受一个回调函数,该函数会被应用到每个元素上,接收三个参数:当前元素、当前索引和数组本身。
function runForEachDemo(): void {
interface Product {
name: string;
price: number;
category: string;
}
const products: Product[] = [
{ name: "手机", price: 2999, category: "电子产品" },
{ name: "笔记本", price: 5999, category: "电子产品" },
{ name: "书籍", price: 59.9, category: "出版物" },
{ name: "耳机", price: 299, category: "配件" }
];
console.log("遍历产品列表:");
// 使用箭头函数
products.forEach((product, index) => {
console.log(
`产品 ${index + 1}: ${product.name} - ¥${product.price} (${product.category})`
);
});
// 使用单独的函数
function printProduct(product: Product, index: number): void {
console.log(
`[第二种方式] 产品 ${index + 1}: ${product.name} - ¥${product.price}`
);
}
products.forEach(printProduct);
// 计算总价
let totalPrice = 0;
products.forEach(product => {
totalPrice += product.price;
});
console.log(`所有产品总价: ¥${totalPrice.toFixed(2)}`);
}
4. 箭头函数
箭头函数是 ES6 引入的简洁函数语法,特点包括:
- 更简洁的语法
- 不绑定自己的 this、arguments、super 或 new.target
- 不能使用 arguments 对象
- 不能作为构造函数使用
function runArrowFunctionDemo(): void {
// 无参数
const greet = (): string => "Hello, TypeScript!";
console.log(greet());
// 单个参数
const square = (x: number): number => x * x;
console.log("5 的平方:", square(5));
// 多个参数
const add = (a: number, b: number): number => a + b;
console.log("3 + 7 =", add(3, 7));
// 多语句函数体
const calculateTotal = (price: number, taxRate: number): string => {
const total = price * (1 + taxRate);
return `总价: ¥${total.toFixed(2)}`;
};
console.log(calculateTotal(19.99, 0.08));
// 返回对象
const createUser = (name: string, age: number) => ({
name,
age,
isAdult: age >= 18
});
console.log("用户信息:", createUser("张三", 25));
// this 绑定示例
class Timer {
seconds = 0;
startWithRegularFunction() {
setInterval(function() {
// this 不指向 Timer 实例
this.seconds++; // 错误
}, 1000);
}
startWithArrowFunction() {
setInterval(() => {
// this 指向 Timer 实例
this.seconds++;
console.log("计时:", this.seconds);
}, 1000);
}
}
const timer = new Timer();
// timer.startWithRegularFunction(); // 会出错
// timer.startWithArrowFunction(); // 正常工作
}
// 执行演示
runEvalDemo();
runDataAttributeDemo();
runForEachDemo();
runArrowFunctionDemo();