Javascript最佳实践
2021-02-12 14:22
标签:ack const invalid alert 其他 大写 type inf 判断 Javascript最佳实践 标签:ack const invalid alert 其他 大写 type inf 判断 原文地址:https://www.cnblogs.com/jxjl/p/12730751.htmlES6赋值语句
let count = 5
let color = "blue"
let values = [1,2,3]
let now = new Date()
let [count, color, values, now] = [5, ‘blue‘, [1,2,3], new Date()]
模块化编程
const name = "Nicholas";
const age = ‘18‘
function sayName(){
console.log(‘名字是:‘ + name + ‘ 年龄:‘ + age)
}
const myInfo = {
name: ‘Nicholas‘,
age: ‘18‘,
sayName: function () {
console.log(‘名字是:‘ + this.name + ‘ 年龄:‘ + this.age)
}
}
const sayName = function sayName(){
console.log(‘名字是:‘ + name + ‘ 年龄:‘ + age)
}
const myInfo = {
name: ‘Nicholas‘,
age: ‘18‘,
sayName
}
合理的类型校验
function sortArray(values){
if (values != null){ //避免!
values.sort(comparator);
}
}
function sortArray(values){
if (values instanceof Array){ //推荐 当然,判断方式还有如:Object.prototype.toString.call(values).slice(8, -1) === ‘Array‘
values.sort(comparator);
}
}
使用常量
const invalid_value_msg = ‘Invalid value!‘
const incalid_value_url = ‘/errors/invalid.php‘
function validate(value){
if (!value){
alert(invalid_value_msg)
location.href = incalid_value_url
}
}
const Constants = {
INVALID_VALUE_MSG: "Invalid value!",
INVALID_VALUE_URL: "/errors/invalid.php"
}
function validate(value){
if (!value){
alert(Constants.INVALID_VALUE_MSG)
location.href = Constants.INVALID_VALUE_URL
}
}
避免不必要的属性查找
const query = window.location.href.substring(window.location.href.indexOf("?")) //此版本查找了6次
const url = window.location.href
const query = url.substring(url.indexOf("?")) //此版本只查找了4次