全栈开发面试总结
|Word Count:857|Reading Time:3mins|Post Views:
JavaScript
js的数组遍历类:forEach、map、filter、reduce都有何区别
简短回答:
- forEach - 只遍历,不返回新数组
- map - 遍历并返回新数组(一一对应)
- filter - 过滤元素,返回符合条件的子数组
- reduce - 累积计算,返回单个汇总值
一句话总结:
- forEach:单纯遍历
- map:变换数组
- filter:筛选数组
- reduce:聚合数组
举例说明:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| const numbers = [1, 2, 3, 4, 5];
numbers.forEach(num => console.log(num * 2));
const doubled = numbers.map(num => num * 2);
const evens = numbers.filter(num => num % 2 === 0);
const sum = numbers.reduce((total, num) => total + num, 0);
|
更直观的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| const users = [ {name: 'Alice', age: 25}, {name: 'Bob', age: 17}, {name: 'Charlie', age: 30} ];
const names = users.map(user => user.name);
const adults = users.filter(user => user.age >= 18);
const totalAge = users.reduce((sum, user) => sum + user.age, 0);
|
reduce参数详解:
1. 基本语法
1
| array.reduce(callback(accumulator, currentValue, index, array), initialValue)
|
2. 参数说明
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, curr, idx, arr) => { console.log(`acc:${acc}, curr:${curr}, idx:${idx}`); return acc + curr; }, 0);
|
3. 不同参数组合
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| const sum1 = numbers.reduce((acc, curr) => acc + curr);
const sum2 = numbers.reduce((acc, curr) => acc + curr, 0);
const withIndex = numbers.reduce((acc, curr, idx) => { return acc + curr + idx; }, 0);
const withArray = numbers.reduce((acc, curr, idx, arr) => { return acc + curr + arr.length; }, 0);
|
4. initialValue的重要性
1 2 3 4 5 6 7 8 9 10 11 12 13
| const numbers = [1, 2, 3];
const sum1 = numbers.reduce((acc, curr) => acc + curr);
const sum2 = numbers.reduce((acc, curr) => acc + curr, 0);
[].reduce((acc, curr) => acc + curr, 0); [].reduce((acc, curr) => acc + curr);
|
5. 实际应用示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| const items = [ {name: 'apple', price: 10}, {name: 'banana', price: 5}, {name: 'orange', price: 8} ];
const total = items.reduce((acc, item) => acc + item.price, 0);
const obj = items.reduce((acc, item, index) => { acc[item.name] = item.price; return acc; }, {});
const max = numbers.reduce((acc, curr) => Math.max(acc, curr));
|
总结: reduce必须至少有acc和curr两个参数,initialValue强烈推荐使用!
B/S和C/S的区别
JSP内置对象是Web容器创建的一组对象
out对象
request对象 //请求处理
response对象 //响应信息到客户端
session对象 //存储用户信息
application对象 //实现共享信息、计数器、投票、多人共享,作用域整个服务器都有效
page对象,exception对象 //Page只用于当前页面,exception做异常处理
无需实例即可使用
动态网页和静态网页的区别