9 条非常强大的 JavaScript 技巧
1、全部替换
我们知道string.replace()函数只会替换第一次出现的位置。在正则表达式末尾添加 /g 即可替换所有出现。
varexample="potatopotato";console.log(example.replace(/pot/,"tom"));//"tomatopotato"console.log(example.replace(/pot/g,"tom"));//"tomatotomato"
2、提取唯一值
使用Set对象和spread操作符可以创建一个新的数组,仅包含唯一的值。
varentries=[1,2,2,3,4,5,6,6,7,7,8,4,2,1]varunique_entries=[...newSet(entries)];console.log(unique_entries);//[1,2,3,4,5,6,7,8]
3、数字转为字符串
只需要将其与空字符串连接。
varconverted_number=5+"";console.log(converted_number);//5console.log(typeofconverted_number);//string
4、字符串转为数字
只需要使用 + 运算符。
注意这个技巧只能在“字符串形式的数字”上使用。
the_string="123";console.log(+the_string);//123the_string="hello";console.log(+the_string);//NaN
5、打乱数组的元素顺序
varmy_list=[1,2,3,4,5,6,7,8,9];console.log(my_list.sort(function(){returnMath.random()-0.5}));//[4,8,2,9,1,3,6,5,7]
6、多维数组扁平化
只需使用spread运算符。
varentries=[1,[2,5],[6,7],9];varflat_entries=[].concat(...entries);//[1,2,5,6,7,9]
7、短路条件
比如下面的例子:
if(available){addToCart();}
只需将变量和函数写到一起即可:
available&&addToCart()
8、动态属性名
原来我以为必须先定义一个对象才能指定动态属性名,其实不需要:
constdynamic='flavour';varitem={name:'Coke',[dynamic]:'Cherry'}console.log(item);//{name:"Coke",flavour:"Cherry"}
9、使用length属性来改变数组大小或清空数组
只需要重写数组的length即可。
要想改变数组大小:
varentries=[1,2,3,4,5,6,7];console.log(entries.length);//7entries.length=4;console.log(entries.length);//4console.log(entries);//[1,2,3,4]
要想清空数组:
varentries=[1,2,3,4,5,6,7];console.log(entries.length);//7entries.length=0;console.log(entries.length);//0console.log(entries);//[]