每个JS开发者都应该使用javascriptoneliner来提高生产力和技能,所以今天我们讨论一些可以在日常开发生活中使用的oneliners。1.对数组进行排序使用sort方法对数组进行排序非常简单。常量数=[2,6,3,7,8,4,0];number.sort();//预期输出:[0,2,3,4,6,7,8]2.检查数组中的值很多时候我们需要检查数组中是否存在该值,用include方法的帮助。常量数组1=[1,2,3];console.log(array1.includes(2));//预期输出:true3。过滤器数组constwords=['spray','limit','elite','exuberant','destruction','present'];constresult=words.filter(wordword.length>6);console.log(result);//预期输出:Array["exuberant","destruction","present"]4.从数组中查找元素如果您只需要一个元素,但您在数组中得到了很多元素,请不要担心JavaScript有find方法。constarray1=[5,12,8,130,44];constfound=array1.find(elementelement>10);console.log(found);//预期输出:125.查找任意元素的索引数组要查找数组中元素的索引,您可以简单地使用indexOf方法。constbeasts=['蚂蚁','野牛','骆驼','鸭子','野牛'];console.log(beasts.indexOf('bison'));//预期输出:16.将数组转换为Stringconstelements=['Fire','Air','Water'];console.log(elements.join(","));//预期输出:"Fire,Air,Water"7.检查数字是偶数还是奇数很容易找出给定数字是偶数还是奇数。constisEven=numnum%2===0;或者constisEven=num!(n&1);8.删除数组中所有重复值非常简单的删除数组中所有重复值的方法constsetArray=arr[...newSet(arr)];constarr=[1,2,3,4,5,1,3,4,5,2,6];setArray(arr);//预期输出:[1,2,3,4,5,6]9.合并多个数组的不同方式//合并但不删除重复constmerge=(a,b)=>orconstmerge=(a,b)=>[...a,...b];//合并删除重复constmerge=(a,b)=>[...newSet(a.concat(b))];或者constmerge=(a,b)=>[...newSet([...a,...b])];10.滚动到页面顶部将页面滚动到顶部的方法有很多种。constgoToTop=()window.scrollTo(0,0,"smooth");或者constscrollToTop=(element)=>element.scrollIntoView({behavior:"smooth",block:"start"});//滚动到页面底部constscrollToBottom=()window.scrollTo(0,document.body.滚动高度);11.复制到剪贴板在网络应用程序中,复制到剪贴板由于方便用户而迅速流行起来。constcopyToClipboard=text(navigator.clipboard?.writeText??Promise.reject)(text);写在最后以上就是我今天分享给大家的11个JavaScript单行编码技巧。我希望你能从他们那里学到新知识。
