声明式编程

命令式编程描述代码如何工作
声明式编程表明想要实现什么目的

例:编写一个 toLowerCase 函数,给定一个包含大写字符串的数组,返回包含相同小写字符串的数组

1
2
3
4
5
6
7
8
9
// 命令式编程
const toLowerCase = input => {
const output = []; // 创建新数组来保存结果
for (let i = 0; i < input.length; i++) {
// 循环遍历输入的数组
output.push(input[i].toLowerCase()); // 把每一项的小写值传入新数组中
}
return output; // 返回新数组
};
1
2
3
4
5
// 声明式编程
const toLowerCase = input =>
input.map(
value => value.toLowerCase() // 把原数组的每一项都变小写
);

显而易见,声明式更易读,更优雅。

React 与 jQuery 等传统 js 框架的区别就在于 React 遵循声明式范式,无须告诉它如何与 DOM 交互。只要声明希望在屏幕上看到的内容,React 就会完成剩下的工作。

0%