在这个由28个部分组成的免费Scrimba课程中学习ES6

As a part of our collaboration with freeCodeCamp, their eminent instructor Beau Carnes has turned their entire ES6 curriculum into an interactive Scrimba course which you can watch today.

作为我们与freeCodeCamp合作的一部分,他们的著名讲师Beau Carnes将他们的整个ES6课程变成了一个互动式Scrimba课程,您现在可以观看。

As you might know, ES6 is just a way to describe newer JavaScript features that weren’t fully and widely accepted until 2017. Now, almost all JavaScript is written using ES6 features, so this course sets you up to become a modern JavaScript developer.

如您所知,ES6只是描述直到2017年才被广泛和广泛接受的新JavaScript功能的一种方法。现在,几乎所有JavaScript都是使用ES6功能编写的,因此,本课程使您成为一名现代JavaScript开发人员。

In this article, I’ll list out the chapters and give you a sentence or two about it. This way you should be able to quickly judge whether this course looks interesting to you.

在本文中,我将列出各章,并为您提供一两个句子。 这样,您应该能够快速判断该课程对您而言是否有趣。

If so, be sure to head over to Scrimba to watch it!

如果是这样,请务必前往Scrimba观看!

1.简介 (1. Introduction)

In the first screencast, Beau gives you a quick intro to the course and himself and talks a little bit about ES6. He also shows you how you can find the curriculum if you’d like to go through it on the freeCodeCamp site as well.

在第一个截屏视频中,Beau向您简要介绍了该课程及其本人,并简要介绍了ES6。 他还向您展示了如何在freeCodeCamp网站上查找课程表。

2.探索var和let关键字之间的差异 (2. Explore Differences Between the var and let Keywords)

The first subject is variables. In ES5 we could only declare variables with var, but starting with ES6 we can now use let and const.

第一个主题是变量。 在ES5中,我们只能使用var声明变量,但是从ES6开始,我们现在可以使用letconst

How are let and var different? let doesn’t allow you to declare a variable twice.

letvar有何不同? let不允许您两次声明变量。

var catName = "Quincy";  
var catName = "Beau";  
// Works fine!

let dogName = "Quincy";  
let dogName = "Beau";  
// Error: TypeError: unknown: Duplicate declaration "dogName"

3.比较var和let关键字的范围 (3. Compare Scopes of the var and let Keywords)

Another major difference between var and let is how they are scoped (freeCodeCamp’s guide on scope).

varlet之间的另一个主要区别是它们的范围( freeCodeCamp的scope指南 )。

When you declare a variable with var it is declared globally or locally if inside a function.

当使用var声明变量时,如果在函数内部,则声明为全局或局部声明。

When it’s declared with let it would be limited to a block statement or expression scope.

当用let声明时,它将限制在block语句或表达式范围内。

Beau shows you two examples.

Beau展示了两个示例。

4.使用const关键字声明一个只读变量 (4. Declare a Read-Only Variable with the const Keyword)

const is a way to assign a read-only variable that cannot be reassigned.

const是分配无法重新分配的只读变量的方法。

const fcc = "freeCodeCamp";  
const sentence = fcc + " is cool!";  
sentence = fcc + " is amazing!";  
// Error: SyntaxError: unknown: "sentence" is read-only

5.突变用const声明的数组 (5. Mutate an Array Declared with const)

You should be careful with const, though as it is still possible to mutate arrays assigned with it.

您应该谨慎使用const ,尽管仍然可以对分配给它的数组进行突变。

const myArray = [5, 7, 2];

myArray[0] = 2;  
myArray[1] = 7;  
myArray[2] = 5;

console.log(myArray);   
// [2, 7, 5]

Same applies to objects.

同样适用于对象。

6.防止物体突变 (6. Prevent Object Mutation)

In order to avoid object and array mutation, you can use Object.freeze():

为了避免对象和数组发生突变,可以使用Object.freeze()

const MATH_CONSTANTS = {  
  PI: 3.14  
};

Object.freeze(MATH_CONSTANTS);  
MATH_CONSTANTS.PI = 99;

// TypeError: Cannot assign to read-only property 'PI' of object '#<Object>'

If you wish to freeze arrays, you can also use Object.freeze() and pass your array, but it might not work on some old browsers.

如果您希望冻结数组,则也可以使用Object.freeze()并传递数组,但是在某些旧的浏览器上可能无法使用。

7.使用箭头函数编写简洁的匿名函数 (7. Use Arrow Functions to Write Concise Anonymous Functions)

ES6 also introduces a shorter way of writing anonymous functions.

ES6还引入了一种较短的编写匿名函数的方式。

// ES5 anonymous function  
var magic = function() {  
  return new Date();  
};

// A shorter ES6 arrow function  
var magic = () => {  
  return new Date();  
};

// And we can shorten it even further  
var magic = () => new Date();

8.使用参数编写箭头函数 (8. Write Arrow Functions with Parameters)

Passing parameters to arrow functions is also easy.

将参数传递给箭头功能也很容易。

var myConcat = (arr1, arr2) => arr1.concat(arr2);

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

9.编写高阶箭头函数 (9. Write Higher Order Arrow Functions)

Arrow functions shine when used with higher order functions, like map(), filter(), reduce().

与高阶函数(例如map()filter()reduce()一起使用时,箭头函数会发光。

10.设置函数的默认参数 (10. Set Default Parameters for Your Functions)

If some of our function parameters can be set to a default value, this is how you can do it in ES6:

如果我们的某些功能参数可以设置为默认值,则可以在ES6中执行以下操作:

// If value parameter is not passed in, it will be assigned to 1.   
function increment(number, value = 1) {  
  return number + value;  
};

console.log(increment(5, 2)); // 7  
console.log(increment(5)); // 6

11.将Rest运算符与函数参数一起使用 (11. Use the Rest Operator with Function Parameters)

Rest operator allows you to create a function that takes a variable number of arguments.

Rest运算符允许您创建一个函数,该函数采用可变数量的参数。

function sum(...args) {  
  return args.reduce((a, b) => a + b);  
};

console.log(sum(1, 2, 3)); // 6  
console.log(sum(1, 2, 3, 4)); // 10

12.使用Spread运算符就地评估数组 (12. Use the Spread Operator to Evaluate Arrays In-Place)

The spread operator looks exactly like the rest operator and looks like this: , but it expands an already existing array into individual parts.

散布运算符看起来与其余运算符完全一样,如下所示: ,但是它将已存在的数组扩展为各个部分。

const monthsOriginal = ['JAN', 'FEB', 'MAR'];

let monthsNew = [...monthsOriginal];  
monthsOriginal[0] = 'potato';

console.log(monthsOriginal); // ['potato', 'FEB', 'MAR']  
console.log(monthsNew); // ['JAN', 'FEB', 'MAR']

13.使用解构分配从对象分配变量 (13. Use Destructuring Assignment to Assign Variables from Objects)

Destructuring is a special syntax for neatly assigning values taken directly from an object to a new variable.

销毁是一种特殊的语法,用于将直接从对象获取的值巧妙地分配给新变量。

// Object we want to destructure  
var voxel = {x: 3.6, y: 7.4, z: 6.54 };

// This is how we would do it in ES5  
var a = voxel.x; // a = 3.6  
var b = voxel.y; // b = 7.4  
var c = voxel.z; // c = 6.54

// A shorter ES6 way  
const { x : a, y : b, z : c } = voxel;   
// a = 3.6, b = 7.4, c = 6.54

14.使用解构分配从嵌套对象分配变量 (14. Use Destructuring Assignment to Assign Variables from Nested Objects)

You can use destructuring to get values out of even nested objects:

您可以使用解构从嵌套对象中获取值:

const LOCAL_FORECAST = {  
  today: { min: 72, max: 83 },  
  tomorrow: { min: 73.3, max: 84.6 }  
};

function getMaxOfTmrw(forecast) {  
  "use strict";

// we get tomorrow object out of the forecast  
  // and then we create maxOfTomorrow with value from max  
  const { tomorrow : { max : maxOfTomorrow }} = forecast;

return maxOfTomorrow;  
}  
console.log(getMaxOfTmrw(LOCAL_FORECAST));  
// 84.6

15.使用解构分配从数组中分配变量 (15. Use Destructuring Assignment to Assign Variables from Arrays)

Do you wonder if destructuring can be used with arrays? Absolutely! There is one important difference though. While destructuring arrays, you cannot specify a value you wish to go into a specific variable and they all go in order.

您是否想知道解构是否可以与数组一起使用? 绝对! 但是有一个重要的区别。 在解构数组时,您无法指定要放入特定变量中的值,并且它们都按顺序排列。

const [z, x, , y] = [1, 2, 3, 4, 5, 6];

// z = 1;  
// x = 2;   
// Skip 3  
// y = 4;

16.与剩余运算符一起使用分解分配来重新分配数组元素 (16. Use Destructuring Assignment with the Rest Operator to Reassign Array Elements)

Let’s now combine the rest operator with destructuring to supercharge our ES6 skills.

现在,让剩下的运算符与解构结合起来,以增强我们的ES6技能。

const list = [1,2,3,4,5,6,7,8,9,10];

// Create a and b out of first two members  
// Put the rest in a variable called newList  
const [ a, b, ...newList] = list;

// a = 1;  
// b = 2;  
// newList = [3,4,5,6,7,8,9,10];

17.使用解构分配将对象作为函数的参数传递 (17. Use Destructuring Assignment to Pass an Object as a Function’s Parameters)

We can create more readable functions.

我们可以创建更具可读性的函数。

const stats = {  
  max: 56.78,  
  standard_deviation: 4.34,  
  median: 34.54,  
  mode: 23.87,  
  min: -0.75,  
  average: 35.85  
};

// ES5  
function half(stats) {  
  return (stats.max + stats.min) / 2.0;  
};

// ES6 using destructuring  
function half({max, min}) {  
  return (max + min) / 2.0;  
};

console.log(half(stats));   
// 28.015

18.使用模板文字创建字符串 (18. Create Strings using Template Literals)

Template literals help us to create complex strings. They use a special syntax of `` and ${} where you can combine template text with variables together. For example `Hello, my name is ${myNameVariable} and I love ES6!`

模板文字帮助我们创建复杂的字符串。 它们使用特殊的语法``${} ,您可以在其中将模板文本与变量组合在一起。 例如`Hello, my name is ${myNameVariable} and I love ES6!`

const person = {  
  name: "Zodiac Hasbro",  
  age: 56  
};

// Template literal with multi-line and string interpolation

const greeting = `Hello, my name is ${person.name}!   
I am ${person.age} years old.`;

console.log(greeting);

19.使用简单字段编写简洁的对象文字声明 (19. Write Concise Object Literal Declarations Using Simple Fields)

ES6 added support for easily defining object literals.

ES6添加了对轻松定义对象文字的支持。

// returns a new object from passed in parameters  
const createPerson = (name, age, gender) => ({  
  name: name,  
  age: age,   
  gender: gender  
});

console.log(createPerson("Zodiac Hasbro", 56, "male"));

// { name: "Zodiac Hasbro", age: 56, gender: "male" }

20.用ES6编写简洁的声明式函数 (20. Write Concise Declarative Functions with ES6)

Objects in JavaScript can contain functions.

JavaScript中的对象可以包含函数。

const ES5_Bicycle = {  
  gear: 2,  
  setGear: function(newGear) {  
    "use strict";  
    this.gear = newGear;  
  }  
};

const ES6_Bicycle = {  
  gear: 2,  
  setGear(newGear) {  
    "use strict";  
    this.gear = newGear;  
  }  
};

ES6_Bicycle.setGear(3);

console.log(ES6Bicycle.gear); // 3

21.使用类语法定义构造函数 (21. Use class Syntax to Define a Constructor Function)

ES6 provides syntax to create objects using the class keyword:

ES6提供了使用class关键字创建对象的语法:

var ES5_SpaceShuttle = function(targetPlanet){  
  this.targetPlanet = targetPlanet;  
}

class ES6_SpaceShuttle {  
  constructor(targetPlanet){  
    this.targetPlanet = targetPlanet;  
  }  
}

var zeus = new ES6_SpaceShuttle('Jupiter');

console.log(zeus.targetPlanet); // 'Jupiter'

22.使用getter和setter来控制对对象的访问 (22. Use getters and setters to Control Access to an Object)

With an object, you often want to obtain values of properties and set a value of a property within an object. These are called getters and setters. They exist to hide some underlying code, as it should not be of concern for anyone using the class.

对于对象,您通常希望获取属性的值并在对象内设置属性的值。 这些被称为gettersetter。 它们的存在是为了隐藏一些基础代码,因为使用该类的任何人都不必担心。

class Thermostat {  
  // We create Thermostat using temperature in Fahrenheit.  
  constructor(temp) {  
    // _temp is a private variable which is not meant   
    // to be accessed from outside the class.  
    this._temp = 5/9 * (temp - 32);  
  }

// getter for _temp  
  get temperature(){  
    return this._temp;  
  }

// setter for _temp  
  // we can update temperature using Celsius.  
  set temperature(updatedTemp){  
    this._temp = updatedTemp;  
  }  
}

// Create Thermostat using Fahrenheit value  
const thermos = new Thermostat(76);  
let temp = thermos.temperature;

// We can update value using Celsius  
thermos.temperature = 26;  
temp = thermos.temperature;  
console.log(temp) // 26

23.了解导入和要求之间的区别 (23. Understand the Differences Between import and require)

In the past, we could only use require to import functions and code from other files. In ES6 we can use import:

过去,我们只能使用require从其他文件中导入函数和代码。 在ES6中,我们可以使用import

// in string_function.js file  
export const capitalizeString = str => str.toUpperCase()

// in index.js file  
import { capitalizeString } from "./string_function"

const cap = capitalizeString("hello!");

console.log(cap); // "HELLO!"

24.使用导出重用代码块 (24. Use export to Reuse a Code Block)

You would normally export functions and variables in certain files so that you can import them in other files — and now we can reuse the code!

通常,您可以将函数和变量export到某些文件中,以便可以将它们导入其他文件中-现在我们可以重用代码了!

const capitalizeString = (string) => {  
  return string.charAt(0).toUpperCase() + string.slice(1);  
}

// Named export  
export { capitalizeString };

// Same line named export  
export const foo = "bar";  
export const bar = "foo";

25.使用*从文件导入所有内容 (25. Use * to Import Everything from a File)

If a file exports several different things, you can either import them individually, or you can use * to import everything from a file.

如果文件导出了几种不同的内容,则可以分别导入它们,也可以使用*导入文件中的所有内容。

This is how you would import all the variables from the file in the previous exercise.

这是您在上一个练习中从文件中导入所有变量的方式。

import * as capitalizeStrings from "capitalize_strings";

26.使用导出默认值创建导出后备 (26. Create an Export Fallback with export default)

We looked at named exports in previous chapters and sometimes there might be a single function or a variable that we want to export from a file — export default, often used as a fallback export too.

我们在前面的章节中介绍了命名导出,有时可能希望从文件中export default单个函数或变量- export default ,也经常用作备用导出。

// In math_functions.js file

export default function subtract(x,y) {  
  return x - y;  
}

27.导入默认导出 (27. Import a Default Export)

If you wish to import export default function from the previous exercise, this is how you would do it.

如果您希望从上一个练习中导入export default功能,这就是您要执行的操作。

Note the absence of {} around the subtract function. Default exports don’t need them.

请注意, subtract函数周围没有{} 。 默认导出不需要它们。

// In index.js file  
import subtract from "math_functions";

subtract(7,4); // returns 3;

28. JavaScript ES6 Outro (28. JavaScript ES6 Outro)

If you’ve reached this far: congratulations! Most people who start courses never finish them, so you can be proud of yourself.

如果您已经到此为止:恭喜! 大多数开始上课的人永远不会完成课程,因此您可以为自己感到自豪。

If you’re looking for your next challenge, you should check out Beau’s course on Regex here!

如果您正在寻找下一个挑战,则应在此处查看Beau在Regex上的课程

Good luck! :)

祝好运! :)



Thanks for reading! My name is Per Borgen, I'm the co-founder of Scrimba – the easiest way to learn to code. You should check out our responsive web design bootcamp if want to learn to build modern website on a professional level.

谢谢阅读! 我叫Per Borgen,我是Scrimba的共同创始人–学习编码的最简单方法。 如果要学习以专业水平构建现代网站,则应查看我们的响应式Web设计新手训练营

翻译自: https://www.freecodecamp.org/news/learn-modern-javascript-in-this-free-28-part-course-7ec8d353eb/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值