小巧office_六个小巧但很棒的ES6功能

小巧office

Everyone in the JavaScript community loves new APIs, syntax updates, and features -- they provide better, smarter, more efficient ways to accomplish important tasks.  ES6 brings forth a massive wave of new goodies and the browser vendors have worked hard over the past year to get those language updates into their browser.  While there are big updates, some of the smaller language updates have put a massive smile on my face; the following are six of my favorite new additions within the JavaScript language!

JavaScript社区中的每个人都喜欢新的API,语法更新和功能-它们提供了更好,更智能,更有效的方式来完成重要任务。 ES6带来了大量新产品,并且浏览器供应商在过去的一年中一直在努力将这些语言更新引入他们的浏览器。 尽管有重大更新,但一些较小的语言更新却令我大笑。 以下是JavaScript语言中我最喜欢的六个新增功能!

1.对象[键]设置语法 (1.  Object [key] setting syntax)

One annoyance JavaScript developers have had for ages is not being able to set a variable key's value within an object literal declaration -- you had to add the key/value after original declaration:

JavaScript开发人员长期以来的一个烦恼就是无法在对象文字声明中设置变量键的值-您必须在原始声明后添加键/值:


// *Very* reduced example
let myKey = 'key3';
let obj = {
    key1: 'One',
    key2: 'Two'
};
obj[myKey] = 'Three';


At best this pattern is inconvenient and at worst it's confusing and ugly.  ES6 provides developers a way out of this mess:

这种模式充其量是不便的,而在最坏的情况下它是令人困惑和丑陋的。 ES6为开发人员提供了摆脱这种混乱的方法:


let myKey = 'variableKey';
let obj = {
    key1: 'One',
    key2: 'Two',
    [myKey]: 'Three' /* yay! */
};


Wrapping the variable key in [] allows developers to get everything done within one statement!

[]包装变量键可以使开发人员在一条语句中完成所有工作!

2.箭头功能 (2.  Arrow Functions)

You don't need to have kept up with every ES6 change to know about arrow functions -- they've been the source of much talk and some confusion (at least initially) to JavaScript developers.  While I could write multiple blog posts to explain each facet of the arrow function, I want to point out how arrow functions provide a method for condensed code for simple functions:

您无需紧跟ES6的每一次更改就可以了解箭头功能-它们一直是JavaScript开发人员大量讨论和困惑的源泉(至少在最初是这样)。 尽管我可以写很多博客文章来解释arrow函数的每个方面,但我想指出arrow函数如何为简单函数的压缩代码提供一种方法:


// Adds a 10% tax to total
let calculateTotal = total => total * 1.1;
calculateTotal(10) // 11

// Cancel an event -- another tiny task
let brickEvent = e => e.preventDefault();
document.querySelector('div').addEventListener('click', brickEvent);


No function or return keywords, sometimes not even needing to add () -- arrow functions are a great coding shortcut for simple functions.

没有functionreturn关键字,有时甚至不需要添加() -箭头函数是简单函数的绝佳编码捷径。

3.查找/查找索引 (3.  find/findIndex)

JavaScript gives developers Array.prototype.indexOf to get the index of a given item within an array, but indexOf doesn't provide a method to calculate the desired item condition; you also need to search for an exact known value.  Enter find and findIndex -- two methods for searching an array for the first match of a calculated value:

JavaScript为开发人员提供了Array.prototype.indexOf来获取数组中给定项目的索引,但是indexOf没有提供计算所需项目条件的方法。 您还需要搜索确切的已知值。 输入findfindIndex用于在数组中搜索计算值的第一个匹配项的两种方法:


let ages = [12, 19, 6, 4];

let firstAdult = ages.find(age => age >= 18); // 19
let firstAdultIndex = ages.findIndex(age => age >= 18); // 1


find and findIndex, through allowing a calculated value search, also prevent unnecessary side effects and looping through possible values!

findfindIndex通过允许搜索计算值,还可以防止不必要的副作用和遍历可能的值!

4.点差运算符: ... (4.  The Spread Operator: ... )

The spread operator signals that an array or iterable object should have its contents split into separate arguments within a call.  A few examples:

传播运算符发出信号,表示数组或可迭代对象的内容应在调用内拆分为单独的参数。 一些例子:


// Pass to function that expects separate multiple arguments
// Much like Function.prototype.apply() does
let numbers = [9, 4, 7, 1];
Math.min(...numbers); // 1

// Convert NodeList to Array
let divsArray = [...document.querySelectorAll('div')];

// Convert Arguments to Array
let argsArray = [...arguments];


The awesome added bonus is being able to convert iterable objects (NodeList, arguments, etc.) to true arrays -- something we've used Array.from or other hacks to do for a long time.

令人敬畏的额外好处是能够将可迭代对象( NodeListarguments等)转换为真正的数组-我们已经使用Array.from或其他黑客工具做了很长时间了。

5.模板文字 (5.  Template Literals)

Multiline strings within JavaScript were originally created by either concatenation or ending the line with a \ character, both of which can be difficult to maintain.   Many developers and even some frameworks started abusing <script> tags to encapsulate multiline templates, others actually created the elements with the DOM and used outerHTML to get the element HTML as a string.

JavaScript中的多行字符串最初是通过串联或以\字符结尾而创建的,而这两种方法都很难维护。 许多开发人员甚至某些框架开始滥用<script>标签来封装多行模板,其他开发人员实际上是使用DOM创建了元素,并使用outerHTML将元素HTML作为字符串获取。

ES6 provides us template literals, whereby you can easily create multiline strings using backticks characters:

ES6为我们提供了模板文字 ,您可以使用反引号字符轻松创建多行字符串:


// Multiline String
let myString = `Hello

I'm a new line`; // No error!

// Basic interpolation
let obj = { x: 1, y: 2 };
console.log(`Your total is: ${obj.x + obj.y}`); // Your total is: 3


Of course template literals allow you to create more than multiline strings, like simple to advanced interpolation, but just the ability to create multiline strings elegantly puts a smile on my face.

当然,模板文字不仅仅可以让您创建多行字符串,就像简单到高级的插值一样 ,但是创建多行字符串的能力优雅地给我带来了笑容。

6.默认参数值 (6.  Default Argument Values)

Providing default argument values in function signatures is an ability provided by many server-side languages like python and PHP, and now we have that ability within JavaScript:

在函数签名中提供默认参数值是许多服务器端语言(例如python和PHP)提供的功能,现在我们在JavaScript中具有该功能:


// Basic usage
function greet(name = 'Anon') {
  console.log(`Hello ${name}!`);
}
greet(); // Hello Anon!

// You can have a function too!
function greet(name = 'Anon', callback = function(){}) {
  console.log(`Hello ${name}!`);

  // No more "callback && callback()" (no conditional)
  callback();
}

// Only set a default for one parameter
function greet(name, callback = function(){}) {}


Other languages may throw a warning if arguments without a default value aren't provided but JavaScript will continue to set those argument values to undefined.

如果未提供没有默认值的参数,其他语言可能会发出警告,但是JavaScript会继续将这些参数值设置为undefined

The six features I've listed here are just a drop in the bucket of what ES6 provides developers but they're features we'll use frequently without thinking anything of it.  It's these tiny additions that oftentimes don't get attention but become core to our coding.

我在这里列出的六个功能只是ES6为开发人员提供的功能中的一小部分,但是它们是我们经常使用的功能,不会考虑任何东西。 这些微小的添加通常不会引起注意,但却成为我们编码的核心。

Did I leave anything out?  Let me know what small additions to JavaScript you love!

我有什么遗漏吗? 让我知道您喜欢JavaScript的哪些小附加功能!

翻译自: https://davidwalsh.name/es6-features

小巧office

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值