javascript
// 1. 固定常量(永远不变的配置,全部用 const)
const BASE_URL = 'https://api.xxx.com'; // 接口地址
const AVATAR_SIZE = 80; // 头像尺寸
const MAX_COUNT = 99; // 最大数量
// 2. 工具函数(用 const 定义)
const formatPrice = (num) => {
return num.toFixed(2);
};
// 3. 页面入口(Page 内部用 const)
Page({
// 数据
data: {
name: '张三',
price: 0.9777
},
// 生命周期
onLoad() {
// 4. 函数内部:不会重新赋值 → 一律 const
const title = '首页';
const formattedPrice = formatPrice(this.data.price);
this.setData({
currentTitle: title,
showPrice: formattedPrice
});
},
// 事件
changeName() {
// 只会改 data,不会重新赋值 → 用 const
const newName = '小程序用户';
this.setData({ name: newName });
},
// 列表循环
showList() {
const list = [1, 2, 3, 4];
// 循环 item 不变 → 用 const
for (const item of list) {
console.log(item);
}
}
});
Const,let和var的区别:
| 关键字 | 能不能重新赋值 | 作用域 | 推荐场景 |
|---|---|---|---|
| const | ❌ 不能 | 块级 | 90% 场景(固定值、对象、数组) |
| let | ✅ 能 | 块级 | 计数器、会变的值 |
| var | ✅ 能 | 函数级 | 不要用 |
在小程序中 的使用逻辑:东西不会变 → const ,东西会变 → let ,永远别用 var。