js一些技巧记录
1.指数运算:
** 运算符
<< 运算符
Math.pow()
console.log (2 **3 );
console.log (2 <<3 -1 );
console.log (Math.pow (2 , 3 ));
2.数字转字符串:
连接一个空字符串
toString() 方法
String() 构造器
let num = 15 ;
console .log (num+'' );
console .log (num.toString ());
console .log (String (num));
3.字符串转数字:
+连接
~~ 连接
parseInt() 方法
Number() 构造器
let str = '15' ;
console .log (+str);
console .log (+true );
console .log (~~str);
console .log (~~true );
console .log (Number (str));
console .log (parseInt (str));
4.判断对象是否为空对象:
JSON字符串比较
JSON .stringify (obj) === "{}"
5.判断字符串是否为子串:
indexOf 包含子串,则返回大于等于0的索引,否则返回-1
正则表达式
new RegExp (substr).test (str)
6.对象数组根据某一属性去重:
filter + map
uniqueFunc (arr, uniKey ) {
const res = new Map ();
return arr.filter (
(item ) => !res.has (item[uniKey]) && res.set (item[uniKey], 1 )
);
},
7.对象数组根据属性返回对象:
findObj (arr, key, value ) {
return arr.find ((item ) => item[key] === value);
},
8.叫“缺值合并”(nullish coalescing)操作符:
求值其先定义的操作数,如果其左操作数不是null或undefined,就返回该值。否则,它会返回右操作数的值。与&&或||操作符类似,??是短路的:它只在第一个操作数求值为null或undefined时才会求值第二个操作数。如果表达式a没有副效应,那么表达式a ?? b等价于:(a !== null && a !== undefined) ? a : b
let a = 1 ;
a ?? 2 ;
null ?? a;
9.中断forEach:
forEach迭代遍历数组时使用return、break等不会终止遍历。可以使利用try catch包裹,然后在forEach中throw错误打断遍历。
10.使用reduce找出数组中最大值:
let arr = [1 , 3 , 6 , 2 ];
arr.reduce ((x, y ) => {
return (x > y) ? x : y;
})
11.解构:
数组解构
let [greeting,,,name] = ["Hello" , "I" , "am" , "Sarah" ];
console .log (greeting);
console .log (name);
let [greeting = "hi" ,name = "Sarah" ] = ["hello" ];
console .log (greeting);
console .log (name);
let a = 3 ;
let b = 6 ;
[a,b] = [b,a];
console .log (a);
console .log (b);
对象解构
let person = {name : "Sarah" , country : "Nigeria" , job : "Developer" };
let {name = "myName" , friend = "Annie" } = person;
console .log (name);
console .log (friend);
let person = {name : "Sarah" , country : "Nigeria" , job : "Developer" };
let {name : foo, job : bar} = person;
console .log (foo);
console .log (bar);
let person = {name : "Sarah" , country : "Nigeria" , job : "Developer" };
let {name :foo = "myName" , friend : bar = "Annie" } = person;
console .log (foo);
console .log (bar);
let person = {
name : "Sarah" ,
place : {
country : "Nigeria" ,
city : "Lagos" },
friends : ["Annie" , "Becky" ]
};
let {name :foo,
place : {
country : bar,
city : x}
} = person;
console .log (foo);
console .log (bar);
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程