javascript代码技巧
操作符
&&操作符
// 繁琐
if (this.isTrue) {
this.test();
}
// 简洁
this.isTrue && this.test();
||操作符
// 繁琐
let num;
if (this.value) {
num = this.value;
} else {
num = 2;
}
// 繁琐
let num = this.value ? this.value : 2;
// 简洁
let num = this.value || 2; // 同上
!操作符
// 繁琐(无效值判断)
if (value == false) {
}
if (value == "") {
}
if (value == 0) {
}
if (value == null) {
}
if (value == undefined) {
}
// 简洁
if (!value) {
}
!!操作符
// 繁琐(布尔值判断)
if (value == true) {
}
if (value == false) {
}
if (Boolean(value)) {
}
// 简洁(布尔值判断)
if (!!value) {
}
拓展运算符
// 对象合并
let obj = { a: 0 };
let obj1 = { a1: 1 };
let obj2 = { a2: 2 };
// 方式一(繁琐)
obj.a1 = obj1.a1;
obj.a2 = obj2.a2;
// 方式二(简洁)
obj = { ...obj1, ...obj2 };
// 数组合并
let arr = [];
let arr1 = [1, 2];
let arr2 = [3, 4];
// 方式一(繁琐)
arr = arr.concat(arr1);
arr = arr.concat(arr2);
// 方式二(简洁)
arr = [...arr1, ...arr2];
解构赋值
// 对象
let res = {
detail: {
a: 1,
b: 2,
c: 3,
},
};
// 方式一(繁琐)
const a = res.detail.a;
const b = res.detail.b;
const c = res.detail.c;
// 方式二(简洁)
const { a, b, c } = res.detail;
// 数组
let arr = [1, 2, 3];
// 方式一(繁琐)
const a = arr[0];
const b = arr[1];
const c = arr[2];
// 方式二(简洁)
const [a, b, c] = arr;
拼接字符串
// 模板字符串
let title = "标题";
let text = "文本";
// 方式一(繁琐)
let htmlStr = "<div>";
"<h1>" + title + "</h1>";
"<p>这是" + text + "</p>";
("</div>");
// 方式二(简洁)
let htmlStr = `
<div>
<h1>${title}</h1>
<p>这是${text}</p>
</div>
`;
数组遍历
const arr = [1, 2, 3];
// 是否所有的都满足
const value = arr.every((value) => value > 2); // false
// 是否有一个满足
const value = arr.some((value) => value > 2); // true
// 获得满足条件的新数组
const value = arr.filter((value) => value > 1); // [2, 3];
// 获得转化后的新数组
const value = arr.map((value) => value * 10); // [10, 20, 30];
// 对数组中所有数求和
const value = numbers.reduce((x, y) => x + y); // 6;
数组去重
// 基础类型值
cosnt nums = [1, 2, 3, 1];
// 方法1
Array.from(new Set(nums)); // [1, 2, 3];
// 方法2
[...new Set(nums)]; // [1, 2, 3];
// 对象类型值
function uniqueArr(arr, key) {
var hash = {};
return arr.reduce(function(item, next) {
hash[next[key]] ? '' : hash[next[key]] = true && item.push(next);
return item
}, []);
}
uniqueArr([{a: 1}, {a: 2}, {a: 3}, {a: 1}], 'a') // [{a: 1}, {a: 2}, {a: 3}]
数组排序
// sort不传参,默认按Unicode进行排序(不推荐)
const arr = ["General", "Tom", "Bob", "John", "Army"];
const resArr = arr.sort();
console.log(resArr); //输出 ["Army", "Bob", "General", "John", "Tom"]
// sort传参-升序(推荐)
const arr = [30, 10, 111, 35, 1899, 50, 45];
arr.sort(function(a, b) {
return a - b;
});
console.log(arr); //输出 [10, 30, 35, 45, 50, 111, 1899]
// sort传参-降序(推荐)
const arr = [30, 10, 111, 35, 1899, 50, 45];
arr.sort(function(a, b) {
return b - a;
});
console.log(arr); //输出 [1899, 111, 50, 45, 35, 30, 10]
对象属性定义
// 动态属性名
const dynamic = "color";
const item = {
brand: "Ford",
[dynamic]: "Blue",
};
console.log(item); // { brand: "Ford", color: "Blue" }
// 带条件的对象属性
const getUser = (emailIncluded) => {
return {
name: "John",
surname: "Doe",
...(emailIncluded ? { email: "john@doe.com" } : null),
};
};
const user = getUser(true);
console.log(user); // outputs { name: "John", surname: "Doe", email: "john@doe.com" }
const userWithoutEmail = getUser(false);
console.log(userWithoutEmail); // outputs { name: "John", surname: "Doe" }
类型判断
// typeof(不能区分复杂类型)
console.log(typeof bool); //boolean
console.log(typeof num); //number
console.log(typeof str); //string
console.log(typeof und); //undefined
console.log(typeof nul); //object
console.log(typeof arr); //object
console.log(typeof obj); //object
console.log(typeof fun); //function
console.log(typeof s1); //symbol
// instanceof(不能识别基础类型)
console.log(bool instanceof Boolean); // false
console.log(num instanceof Number); // false
console.log(str instanceof String); // false
console.log(und instanceof Object); // false
console.log(nul instanceof Object); // false
console.log(arr instanceof Array); // true
console.log(obj instanceof Object); // true
console.log(fun instanceof Function); // true
console.log(s1 instanceof Symbol); // false
// constructor(有局限 => constructor可以被篡改,null、undefined没有construstor)
console.log(bool.constructor === Boolean); // true
console.log(num.constructor === Number); // true
console.log(str.constructor === String); // true
console.log(arr.constructor === Array); // true
console.log(obj.constructor === Object); // true
console.log(fun.constructor === Function); // true
console.log(s1.constructor === Symbol); //true
// Object.prototype.toString.call(全面可靠)
const isType = (value) => Object.prototype.toString.call(value).toLowerCase();
isType(null); // '[object null]'
isType(undefined); // '[object null]'
isType([]); // '[object array]'
isType({}); // '[object object]'
isType(1); // '[object number]'
isType("1"); // '[object string]'
isType(true); // '[object boolean]'
类数组转数组
const doms = document.querySelectorAll("div");
// 方法1(繁琐)
const new_arr = Array.prototype.slice.call(doms);
// 方法2(简洁)
const new_arr = [...doms];
浅拷贝
// 方法1(繁琐)
function simpleCopy() {
var c = {};
for (var i in p) {
c[i] = p[i];
}
return c;
}
// 方法2(相对简洁)
Object.assign({}, obj);
// 方法3(相当简洁)
{ ...obj }
深拷贝
// 方法1(繁琐)
function deepCopy() {
// ...省略
}
// 方法2(相对简洁,但不能复制函数)
JSON.parse(JSON.stringify(obj));
// 方法3(相对简洁,但靠谱)
import _ from "lodash";
_.cloneDeep(obj);
求最大值
const nums = [1, 2, 3, 1];
// 方法1
Math.max.apply(null, num); // 3;
// 方法2
Math.max(...num); // 3;
vue
基础技巧
原型注入
// main.js入口文件内
import Vue from "vue";
import router from "./router";
import store from "./store";
import dayjs from "dayjs";
import App from "./App";
// 将dayjs注入到Vue原型上,方便vue组件内进行this.dayjs获取
Vue.prototype.dayjs = dayjs;
new Vue({
router,
store,
render: (h) => h(App),
}).$mount("#app");
对象冻结
用于纯列表渲染,数据无交互的情况,可以禁止 vue 劫持绑定,节省内存,提升性能
<script>
import * as Api from "@/common/apiNew.js";
export default {
data() {
return {
dataList: Object.freeze(this.list),
};
},
methods: {},
};
</script>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具