当前位置: 首页 > 科技观察

五分钟带你掌握Web前端开发的9个JavaScript技巧

时间:2023-03-13 07:05:46 科技观察

1。全部替换我们知道string.replace()函数只替换第一次出现的地方。您可以通过在正则表达式末尾添加/g来替换所有匹配项。varexample="potatopotato";console.log(example.replace(/pot/,"tom"));//"番茄土豆"console.log(example.replace(/pot/g,"tom"));//《tomatotomato》2.提取唯一值通过使用Set对象和展开运算符,我们可以创建一个具有唯一值的新数组。varentries=[1,2,2,3,4,5,6,6,7,7,8,4,2,1]varunique_entries=[...newSet(entries)];控制台日志(unique_entries);//[1,2,3,4,5,6,7,8]3。要将数字转换为字符串,我们只需要使用带空引号的连接运算符。varconverted_number=5+"";console.log(converted_number);//5console.log(typeofconverted_number);4.要将字符串转换为数字,我们只需要+运算符。请注意,它仅适用于“字符串数字”。the_string="123";console.log(+the_string);//123the_string="hello";console.log(+the_string);//NaN5.随机排列数组中的元素我每天都这样做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.将多维数据展平数组只需使用扩展运算符。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.使用长度调整//空数组我们基本上覆盖了数组的长度。如果我们想调整数组的大小: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);//[]