适用于您日常工作流程的 ESEST 提示、技巧、最佳实践和代码片段示例

适用于您日常工作流程的 esest 提示、技巧、最佳实践和代码片段示例

es6 (ecmascript 2015) 对 javascript 进行了重大改革,引入了许多新功能,可以简化您的编码并提高项目的整体质量。

在这篇文章中,我们将介绍一些es2015 提示、技巧、最佳实践,并提供代码片段示例来增强您的日常工作流程。

1. 声明变量:let 和 const var

在 es5 中,变量是使用 var 声明的,它具有函数作用域的行为,导致提升和作用域可见性问题。 es6 引入了具有块作用域的 let 和 const,提供了对变量声明的更好控制。

常量

定义常量变量:

const variablename = "value"

常量变量不能更改、重新分配或重新定义:

const variablename = "other value"  
   //-->syntaxerror: identifier 'variablename' has already been declared
variablename = "other value" 
   //-->typeerror: assignment to constant variable.

您可以更改、向常量数组添加值,但不能重新分配或重新定义它:

const arrayname = [1,2,3,4]
arrayname.push(5) 
   // output -->[1,2,3,4,5]
const arrayname = [9,8,7,6] 
   //-->syntaxerror: identifier 'arrayname' has already been declared

您可以更改常量对象、为其添加值,但不能重新分配或重新定义它:

const person = {name:"developer",email:"developer@developer.com",city:"new delhi"}
person.name ="developer 2" //change a property 
person.location = "gurugram" //add a new property
person = {name:"dilip",email:"dilip@abc.com",city:"delhi"} //reassign it 
   //-->syntaxerror: identifier 'arrayname' has already been declared

常量变量存在于块作用域中:

var x = 1
{ //this is a block scope
    const x = 2
}
console.log(x) 
    //output -->1

让:

定义一个let变量:

let variablename = "value"

让变量存在于块作用域中:

var x = 1
{ //this is a block scope
    let x = 2
}
console.log(x) //output -->1

let 变量不能重新定义,但可以重新赋值:

let variablename = "other value"  
    //-->syntaxerror
variablename = "other value"

提升 - var 与 let:

var 定义的变量被提升到顶部

console.log(sayhello)
    //output -->undefined
//variable sayhello is hoisted at the top before it was defined by var
//this means that variable is there but with value of undefined
var sayhello = "hello world" 
console.log(sayhello)
    //output -->"hello world"

let 定义的变量不会被提升到顶部

console.log(sayhello)
     //-->referenceerror: cannot access 'sayhello' before initialization/defined
let sayhello = "hello world"
console.log(sayhello)
    //output -->"hello world"

for循环中应该使用let而不是var,因为var定义的变量会泄漏到for循环之外,并且只有在有settimeout函数时才会引用i的最终结果:

var

for (var i = 0; i the number is 2  (x3)   
//settimeout reference i after when the for loop ends
console.log(i)
    //--> 2
//i is leaked outside the for loop

与let

for (let i = 0; i the number is 0
    //-->the number is 1
    //-->the number is 2

最佳实践:对于不会改变的变量使用const,对于需要在特定块内改变的变量使用let。避免使用 var 以防止与作用域相关的问题。


2. 箭头功能

箭头函数是一种定义函数的新方法,代码更简洁,常用于回调函数。
箭头函数允许我们编写更短的函数语法。
定义一个带有 return 的箭头函数:

let myfunction = (a, b) => {
  sum = a * b;
  return sum;
}

定义一个不带返回值的箭头函数:

let myfunction = (a, b) => a * b;

如果没有参数,可以直接使用括号:

let myfunction = () => ("hello world");  

es6 之前的方式相同

function functionname(param1,param2){
     return param1+param2;
}

回调函数中常用箭头函数:

let myarr = [1,2,3]
let doublethenfilter = arr => arr.map((value) => (value * 2) )
                                  .filter((value) => (value % 3 === 0));
doublethenfilter(myarr)

es6 之前的方式相同

function doublethenfilter(arr){
    return arr.map(function(value){
        return value *2;
    }).filter(function(value){
        return value % 3 === 0;
    })
};

最佳实践:使用箭头函数作为匿名函数和回调,以使代码更短并避免出现问题。


3. 模板文字与字符串连接

在 es5 中,字符串连接需要使用 +,这使得管理复杂或多行字符串变得困难。 es6 引入了模板文字,允许使用反引号嵌入表达式和多行字符串。
模板文字使用反引号 (` `) 而不是引号 ("") 来定义字符串。
模板字符串是您处理字符串的快速方法。
您可以引用变量:

let first = "dilip";
let last = "mishra";

console.log(`hello, ${first} ${last}`);
//output --> "hello, dilip mishra"

es6 之前的方式相同:

let first = "dilip";
let last = "mishra";
var greeting = 'hello, ' + name + '!';

console.log('hello, ' + first + ' ' +last);  
//output --> "hello, dilip mishra"

模板文字允许在字符串中使用单引号和双引号:

模板文字允许多行字符串。
你可以只换行,使用 tab 而不使用 n t :

let text =
'the quick
brown fox
jumps over
the lazy dog';
  //output -->  "the quick
brown fox
jumps over
the lazy dog"

模板文字允许在字符串中表达:

let price = 10;
let vat = 0.25;

let total = 'total: ${(price * (1 + vat)).tofixed(2)}';
  //output -->  "total: 12.50"

最佳实践:在处理涉及动态内容或跨多行的字符串时,使用模板文字以获得更好的可读性。


4. 解构赋值与传统访问

解构允许您将数组和对象中的值解压到变量中,从而减少重复代码并增强可读性。

定义与属性同名的变量并赋值:

const person = { name: 'john', age: 30 };
const { name, age } = person;

console.log(name, age);  //output --> john 30

定义属性并为具有不同名称的变量赋值:

const person = { name: 'john', age: 30 };
const { name:username, age:userage } = person;

console.log(username, userage);  //output --> john 30

es6 之前的方式相同

var person = { name: 'john', age: 30 };
var name = person.name;
var age = person.age;

console.log(name, age);  //output --> john 30

数组解构将数组中的值分配给不同的变量:

var arr = [1,2,3];
var [a,b,c] = arr;
console.log(a); //-->1
console.log(b); //-->2
console.log(c); //-->3

最佳实践:使用解构可以更清晰、更直观地访问数组和对象的属性。


5. 默认参数与回退逻辑

es5 需要手动回退逻辑来处理缺失的函数参数,而 es6 引入了默认参数来直接在函数签名中定义回退值。

es5:

function myfunction(x, y) {
  var y = y || 10;
  return x + y;
}
myfunction(5); // will return 15

es6

function myfunction(x, y = 10) {
  // y is 10 if not passed or undefined
  return x + y;
}
myfunction(5); //output --> will return 15

最佳实践:使用默认参数干净地处理可选函数参数。


6. spread 运算符与 concat() 或 apply()

扩展运算符 (...) 允许更简单地合并数组和对象,并且比使用 concat() 或 apply() 更加直观。

es5:

var arr1 = [1, 2];
var arr2 = [3, 4];
var combined = arr1.concat(arr2);

console.log(combined);  // [1, 2, 3, 4]

es6

const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = [...arr1, ...arr2];

console.log(combined);  // [1, 2, 3, 4]

扩展运算符会将数组分解为值,以便可以轻松使用它们:

let nums = [4,5,6];
let nums2 = [1,2,3,...nums,7,8];
console.log(nums2);
    //--> [1,2,3,4,5,6,7,8]

扩展运算符通常在函数不接受数组作为参数时使用:

function sumvalues(a,b,c){
     console.log(arguments);  //print out an array of the arguments of the function
return a+b+c;
}
let nums = [2,3,4];
sumvalues(...nums); //values 2,3,4 of nums array has been passed to a,b,c parameters
    //-->[2,3,4]
    //-->9
sumvalues(5,5,...nums); //value 2 of nums array has been passed to c parameter
    //-->[5,5,2,3,4]
    //-->12

另一个例子

let nums = [1,2,3,4];
math.min(nums);
    //--> nan
math.min(...nums);
    //-->1

最佳实践:使用展开运算符进行数组串联、克隆对象以及将变量参数传递到函数中。


7. promise 与 callbacks

在 es5 中,异步操作通常通过回调来处理,从而导致复杂的“回调地狱”情况。 es6 引入了 promises,它简化了异步代码。

es5:

function fetchdata(callback) {
  settimeout(function() {
    callback('data loaded');
  }, 1000);
}

fetchdata(function(data) {
  console.log(data);  // data loaded
});

es6

function fetchdata() {
  return new promise((resolve, reject) => {
    settimeout(() => resolve('data loaded'), 1000);
  });
}

fetchdata().then(data => console.log(data));  // data loaded

最佳实践:对异步代码使用 promise(以及现代代码中的 async/await),因为它们提供了更清晰、更易于管理的方法。


8. 类与构造函数

es6 引入了类语法作为面向对象编程的构造函数的语法糖。这提供了一种更清晰、更直观的方式来定义和继承类。

es5:

function person(name, age) {
  this.name = name;
  this.age = age;
}

person.prototype.greet = function() {
  return 'hello, i am ' + this.name;
};

var john = new person('john', 30);
console.log(john.greet());  // hello, i am john

es6

class person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    return `hello, i am ${this.name}`;
  }
}

const john = new person('john', 30);
console.log(john.greet());  // hello, i am john

最佳实践: javascript 中使用 oop 模式时,使用类来处理对象创建和继承。


9. 模块(导入/导出)与 iife 或全局函数

es6 之前,javascript 没有原生模块支持。开发人员必须使用立即调用函数表达式 (iife) 或依赖全局变量。 es6 引入了导入和导出,允许模块化代码组织。

es5(iife):

(function() {
  function add(x, y) {
    return x + y;
  }
  window.add = add;
})();

console.log(add(2, 3));  // 5

es6(模块):

// math.js
export function add(x, y) {
  return x + y;
}

// main.js
import { add } from './math.js';
console.log(add(2, 3));  // 5

最佳实践:使用 es6 模块来实现更好的代码组织、可重用性和更轻松的依赖管理。


10. 异步/等待

异步

放置在函数之前的 ansync 关键字使该函数的行为类似于 promise

async function myfunc(){
    return "this is a promise";
}
myfunc().then((val)=>{console.log(val)});
    //-->"this is a promise"

在异步函数中,return 关键字将充当 promise 中的resolve 关键字, throw 关键字将充当 promise 中的reject 关键字

async function dohomework(){
    let isdone = false;
    if (isdone){
        return("is done");
    }else{
        throw "is not done";
    }
}
dohomework().then(function(homeworkresult){
    console.log("the homework " + homeworkresult);
}).catch(function(homeworkresult){
    console.log("the homework " + homeworkresult);
})
    //"the homework is not done"

等待

await 关键字仅在 async 函数中使用。 wait 关键字使您的代码等待,直到函数内的 promise 被履行/拒绝:

async function myFunc(){
    let myPromise = new Promise((resolve,reject)=>{
        setTimeout(()=>{resolve("done!")},1000)
    });
    let result = await myPromise; //wait for this promise before continuing
    return result;
}
myFunc().then((result)=>{console.log(result)})


最后的想法

es6 极大地改进了 javascript 的编写和维护方式。在日常工作流程中采用这些技巧和实践不仅会使您的代码更简洁,而且更易于维护和扩展。无论您是从 es5 切换还是增强 es6 技能,这些技巧都将帮助您保持生产力。

欢迎投稿!如果您根据自己的经验有其他提示、技巧或用例,请随时在评论中分享。

编码愉快!

以上就是适用于您日常工作流程的 ESEST 提示、技巧、最佳实践和代码片段示例的详细内容,更多请关注www.sxiaw.com其它相关文章!