首页>国内 > 正文

11 个JavaScript专业技巧,让你成为更好的开发者

2023-03-28 06:13:24来源:web前端开发

如果您想提高 JavaScript 技能并成为更好的开发人员,那么本文适合您。本文将教您 11 个专业技巧,帮助您编写更好的 JavaScript 代码,你还在等什么?一起来学习吧。


【资料图】

1. 使用 XOR 运算符比较数字

按位异或运算符 (^) 对两个操作数执行按位异或运算。这意味着如果位不同则返回 1,如果相同则返回 0。

const a = 1337;const b = 69;// noobya !== 69 ? console.log("Unequal") : console.log("Equal");  // Unequalb !== 69 ? console.log("Unequal") : console.log("Equal");  // Equal// proa ^ 69 ? console.log("Unequal") : console.log("Equal");    // Unequalb ^ 69 ? console.log("Unequal") : console.log("Equal");    // Equal
2. 用数据即时创建和填充数组
// noobyconst array = new Array(3);for(let i=0; i < array.length; i++){    array[i] = i;}console.log(array)  // [ 0, 1, 2 ]// proconst filledArray = new Array(3).fill(null).map((_, i)=> (i));console.log(filledArray)  // [ 0, 1, 2 ]
3. 使用对象中的动态属性
// noobylet propertyName = "body";let paragraph = {    id: 1,};paragraph[propertyName] = "other stringy";// { id: 1, body: "other stringy" }console.log(paragraph)// prolet propertyName = "body";let paragraph = {    id: 1,    [propertyName] : "other stringy"};// { id: 1, body: "other stringy" }console.log(paragraph)
4. 轻松消除数组中的重复值

您可以使用集合消除数组中的重复值。

// noobylet answers = [7, 13, 31, 13, 31, 7, 42];let leftAnswers = [];let flag = false;for (i = 0; i< answers.length; i++) {    for (j = 0; j < leftAnswers.length; j++) {        if (answers[i] === leftAnswers[j]) {            flag = true;        }    }    if (flag === false) {        leftAnswers.push(answers[i]);    }    flag = false;}//[ 7, 13, 31, 42 ]console.log(leftAnswers)// prolet answers = [7, 13, 31, 13, 31, 7, 42];let leftAnswers = Array.from(new Set(answers));// [ 7, 13, 31, 42 ]console.log(leftAnswers)
5. 轻松地将对象转换为数组

您可以使用展开运算符将数组转换为对象。

// noobylet arr = ["v1", "v2", "v3"];let objFromArray = {};for (let i = 0; i < arr.length; ++i) {    if (arr[i] !== undefined) {        objFromArray[i] = arr[i];    }}// { "0": "v1", "1": "v2", "2": "v3" }console.log(objFromArray)// prolet objFromArrayPro = {...arr};// { "0": "v1", "1": "v2", "2": "v3" }console.log(objFromArrayPro)
6. 使用逻辑运算符进行短路评估

您可以使用逻辑运算符进行短路评估,方法是使用 && 运算符返回表达式链中的第一个假值或最后一个真值,或者使用 || 运算符返回表达式链中的第一个真值或最后一个假值。

const dogs = true;// noobyif (dogs) {    runAway();}// prodogs && runAway()function runAway(){    console.log("You run!");}
7. 对象键维护它们的插入顺序

对象键通过遵循一个简单的规则来维护它们的插入顺序:类整数键按数字升序排序,而非类整数键根据它们的创建时间排序。

const character = {    name: "Arthas",    age: 27,    class: "Paladin",    profession: "Lichking",};// name age class professionconsole.log(Object.keys(character));
8. 创建并填充指定大小的数组

您可以使用带有两个参数的 Array() 构造函数来创建和填充指定大小和值的数组:大小和值,或者对空数组使用 Array.fill() 方法。

// noobyconst size = 5;const defaultValue = 0;const arr = []for(let i = 0; i < size; i++){    arr.push(defaultValue)}console.log(arr);// proconst size = 5;const defaultValue = 0;const arr = Array(size).fill(defaultValue);console.log(arr); // [0, 0, 0, 0, 0]
9. 理解 JavaScript 中的 Truthy 和 Falsy 值

在布尔上下文中使用时,Truthy 和 Falsy 值会隐式转换为 true 或 false。

虚假值 => false, 0, ""(空字符串), null, undefined, &NaN

真值 => "Values", "0", {}(空对象),&[](空数组)

// proif(![].length){    console.log("There is no Array...");} else {    console.log("There is an Array, Hooray!");}if(!""){    console.log("There is no content in this string...");} else {    console.log("There is content in this string, Hooray!");}
10. 用更好的参数改进函数

不要使用单个多个参数,而是使用参数对象。在函数定义中解构它以获得所需的属性。

// noobyfunction upload(user, resourceId, auth, files) {}upload(...); // need to remember the order// profunction upload(    { user, resourceId, auth, files } = {}) {}const uploadObj = {    user: "me",    resourceId: uuid(),    auth: "token",    files: []}upload(uploadObj);
11. Null 和 Undefined 在 JavaScript 中是不同的

Null 和 undefined 是两个不同的值,表示没有值。

null => 是的,这是一个值。Undefined 不是将 null 想象成在一个空盒子前面把 undefined 想象成在没有盒子的前面
const fnExpression = (s = "default stringy") => console.log(s);fnExpression(undefined); // default stringyfnExpression(); // default stringyfnExpression(null); // null
总结

以上就是我今天想与您分享的11个关于JavaScript的专业技巧,希望您能从中学到新东西。

关键词:

相关新闻

Copyright 2015-2020   三好网  版权所有 联系邮箱:435 22 640@qq.com  备案号: 京ICP备2022022245号-21