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

9个有用的JavaScript技巧

时间:2023-03-13 11:43:57 科技观察

黑客的方法论是一种涉及持续改进和迭代的构建方法。黑客认为总有一天它会变得更好,没有什么是不可能的。真正的黑客总是用不同的方法来解决没人注意的问题。下面给出了一些非常强大的JavaScript技巧。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);//string4.要将字符串转换为数字,只需使用+运算符。但要注意:它只适用于“字符串数字”。the_string="123";console.log(+the_string);//123the_string="hello";console.log(+the_string);//NaN5.随机排列数组中的元素,这样最适合shuffle: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:"可乐”,味道:“樱桃”}9。使用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);//[]