5个能提高前端工作效率的操作

时间:2021-05-02

一些在前端项目中会用到的快捷操作,下面的代码都可以直接复制到控制台运行。

数字取整

letfloatNum=100.5;

letintNum=~~floatNum;

console.log(intNum);//100

字符串转数字

letstr="10000";

letnum=+str;

console.log(num);//10000

Falsy和Truthy值转boolean

Falsy为Javascript中所有可以转换为false的值的统称,共8个:false本身、空字符串、null、undefined、NaN、数字0、数字-0、大数字0n。

除Falsy值外其他所有值都是Truthy

letfalseNum=0;

letfalseStr="";

letfalseUndefined;

letfalseNull=null;

letfalseNaN=0/0;

lettrueNum=1;

lettrueStr="何方";

lettrueObj={name:"何方"};

lettrueArr=["前端","后端"];

console.log("falseNum",!!falseNum);//false

console.log("falseStr",!!falseStr);//false

console.log("falseUndefined",!!falseUndefined);//false

console.log("falseNaN",!!falseNaN);//false

console.log("trueNum",!!trueNum);//true

console.log("trueStr",!!trueStr);//true

console.log("trueObj",!!trueObj);//true

console.log("trueArr",!!trueArr);//true

交换对象键值

letobj={

key1:"value1",

key2:"value2"

};

letrevert={};

Object.entries(obj).forEach(([key,value])=>revert[value]=key);

console.log(revert);

数组去重

值类型数组

letarrNum=[

1,2,3,4,5,6,7,8,9,0,

1,2,3,4,5,6,7,8,9,0

];

letarrString=[

"1","2","3","4","5","6","7","8","9","0",

"1","2","3","4","5","6","7","8","9","0"

];

letarrMixed=[

1,"1","2",true,false,false,1,2,"2"

];

arrNum=Array.from(newSet(arrNum));

arrString=[...newSet(arrString)];

arrMixed=[...newSet(arrMixed)];

console.log(arrNum);//[1,2,3,4,5,6,7,8,9,0]

console.log(arrString);//["1","2","3","4","5","6","7","8","9","0"]

console.log(arrMixed);//[1,"1","2",true,false,2]

引用类型数组

letarrObj=[

{name:"何方"},

{name:"王二"},

{name:"何方"},

{name:"何方"},

{name:"何方"},

{name:"何方"},

{name:"王二"},

{name:"王二"},

{name:"王二"},

{name:"王二"},

];

letarrObj2=[];

arrObj.forEach(item=>{

arrObj2.find(find=>find.name===item.name)||arrObj2.push(item)

});

console.log(arrObj2);

原文地址:https://www.toutiao.com/a6914823899238875655/

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章