前端面试三之控制语句
1.for-in
for...in
是 JavaScript 中用于遍历对象可枚举属性的循环语句。它主要用于遍历对象的属性名(键),而不是属性值。
(1)遍历对象属性
const person = {name: 'Alice',age: 25,job: 'Developer'
};for (const key in person) {console.log(`${key}: ${person[key]}`);
}
// 输出:
// name: Alice
// age: 25
// job: Developer
2.for-of
for...of
是 ES6 (ECMAScript 2015) 引入的循环语句,用于遍历可迭代对象(如数组、字符串、Map、Set 等)的元素值。for...of
是现代 JavaScript 中遍历集合数据的首选方式,提供了更简洁、更直观的语法,特别适合处理数组和其他可迭代对象。
(1)遍历数组
const fruits = ['apple', 'banana', 'orange'];for (const fruit of fruits) {console.log(fruit);
}
// 输出:
// apple
// banana
// orange
(2)遍历字符串
const str = 'hello';for (const char of str) {console.log(char);
}
// 输出:
// h
// e
// l
// l
// o
(3)结合解构赋值
const users = [{ name: 'Alice', age: 25 },{ name: 'Bob', age: 30 }
];for (const { name, age } of users) {console.log(`${name} is ${age} years old`);
}
(4)与 for...in
的区别
特性 | for...of | for...in |
---|---|---|
用途 | 遍历可迭代对象的值 | 遍历对象属性名 |
获取内容 | 属性值 | 属性名(键) |
原型链属性 | 不涉及原型链 | 会遍历继承的可枚举属性 |
数组使用 | 只遍历数字索引元素 | 遍历所有可枚举属性(包括非数字键) |
适用对象 | 可迭代对象(Array, Map, Set等) | 任意对象 |
3.try-catch
try-catch
是 JavaScript 中处理运行时错误的异常处理机制,允许你"尝试"执行可能出错的代码,并"捕获"处理可能发生的异常,防止程序意外终止。
try {// 可能抛出错误的代码
} catch (error) {// 错误处理代码
} finally {// 无论是否出错都会执行的代码
}
(1)基本错误捕获
try {console.log(notDefined); // 引用未定义变量
} catch (error) {console.error('发生错误:', error.message);// 输出: "发生错误: notDefined is not defined"
}
(2)使用 finally
块
let file = openFile();
try {processFile(file);
} catch (error) {console.error('文件处理失败:', error);
} finally {closeFile(file); // 确保文件总是被关闭
}