销毁和功能参数

    技术2022-07-11  123

    The JavaScript language has benefitted from some really awesome new features over the past few years, including arrow functions, the spread operator, and default function argument values.  Even if your browser doesn't yet support proposed JavaScript API syntax additions, you can use a tool like Babel in your Node.js app to take advantage of them today.

    在过去的几年中,JavaScript语言受益于一些非常了不起的新功能,包括箭头函数,扩展运算符和默认函数参数值 。 即使您的浏览器尚不支持建议JavaScript API语法添加功能,您也可以在Node.js应用中使用Babel之类的工具来立即利用它们。

    One of my favorite new(ish) JavaScript features is object destructuring.  If you aren't familiar with JavaScript destructuring, it basically provides a shorter syntax for extracting an object key's value without the dot notation mess:

    我最喜欢JavaScript新功能之一是对象分解。 如果您不熟悉JavaScript解构,那么它基本上提供了一种较短的语法来提取对象键的值,而不会引起点符号混乱:

    // A sample object const myObject = { x: 1, y: 2 }; // Destructuring const { x, y } = myObject; // x is 1, y is 2

    The basic syntax for destructuring is fairly simple but using destructuring with function arguments can be a bit more difficult when those argument values should have default values.  The following is a function with arguments having default values:

    销毁的基本语法相当简单,但是当这些参数值应具有默认值时,对函数参数使用销毁可能会更加困难。 以下是带有默认值的参数的函数:

    function myFunction(text = "", line = 0, truncate = 100) { // With default values, we can avoid a bunch of: text = text || ""; line = line || 0; truncate = truncate || 100; }

    Regardless of language, if a function takes more than ~3 parameters, it's probably best to pass in an object name options or config that contains possible key/values; the equivalent would look like:

    无论使用哪种语言,如果一个函数使用的参数超过约3个,则最好传入包含可能的键/值的对象名称options或config 。 等效形式如下:

    function myFunction(config) { } // Usage myFunction({ text: "Some value", line: 0, truncate: 100 })

    What if you want to use destructuring in JavaScript function arguments though?  The following function signature would become:

    但是,如果您想在JavaScript函数参数中使用解构怎么办? 以下功能签名将变为:

    function myFunction({ text, line, truncate }) { }

    If you want to define defaults in the function configuration, you'd use the following:

    如果要在功能配置中定义默认值,请使用以下命令:

    function myFunction({ text = "", line = 0, truncate = 100 } = {}) { // Even if the passed in object is missing a given key, the default is used! }

    Setting a default with = { } is important; with no default the following example would error:

    用= { }设置默认值很重要; 如果没有默认值,则以下示例将出错:

    TypeError: Cannot destructure property `key` of 'undefined' or 'null'

    Destructuring is an awesome language feature but can lead to confusion and even errors.  Hopefully the basics provided in this guide can help you to navigate using JavaScript destructuring with functions!

    销毁是一种很棒的语言功能,但可能导致混乱甚至错误。 希望本指南中提供的基础知识可以帮助您使用带有功能JavaScript解构进行导航!

    翻译自: https://davidwalsh.name/destructuring-function-arguments

    相关资源:jdk-8u281-windows-x64.exe
    Processed: 0.009, SQL: 9