功能的JavaScript默认参数

编程入门 行业动态 更新时间:2024-10-09 08:29:53
本文介绍了功能的JavaScript默认参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我完全理解ECMAScript 6已经创造了很多潜在的处理方式,如箭头功能。

由于我不是很熟悉新的当谈论功能的默认参数时。功能1:

code>函数m1({x = 0,y = 0} = {}){ return [x,y]; }

功能2:

函数m2({x,y} = {x:0,y:0}){ return [x,y]; }

解决方案

尝试传递一些东西到你的函数:

m1({})// [0,0] m1({ z:1})// [0,0] m1({x:1})// [1,0] m2({})// [undefined,undefined ] m2({z:1})// [undefined,undefined] m2({x:1})// [1,undefined]

您的第一个语法( m1({x = 0,y = 0} = {}) )做了三件事:

  • 首先,它为函数提供一个默认的第一个参数,这是一个空对象。如果没有给出第一个参数( m1()),则使用默认的空对象(即,它变为 m1({}))
  • 其次,您的代码提取 x 和 y
  • 如果任何一个是 undefined ,它将被赋予默认值 0 。

m2({x,y} = {x:0,y:0 })做了不同的事情:

  • 首先它为函数提供一个默认的第一个参数,对象 {x:0,y:0} 。如果没有传入第一个参数,则使用该对象。如果除未定义之外的任何参数都被传递,那么使用该值。
  • 其次,代码提取 x 和 y 属性。如果他们是 undefined ,那就是你会得到的。

选项(具有使用更多默认值进行破坏的默认值的参数)几乎是您想要的。第二个选项意味着如果传递参数,则您的代码对于属性没有明智的/有用的默认值。

I can fully understand ECMAScript 6 has created a lot of potential way of handling with functions such as arrow functions.

Since I'm not very familiar with the new stuff, when talking about default parameters for a function. How to interpret the differences between the following way of defining functions:

Function 1:

function m1({x = 0, y = 0} = {}) { return [x, y]; }

Function 2:

function m2({x, y} = { x: 0, y: 0 }) { return [x, y]; }

解决方案

The difference is clear when you try passing something to your functions:

m1({}) // [0, 0] m1({z: 1}) // [0, 0] m1({x: 1}) // [1, 0] m2({}) // [undefined, undefined] m2({z: 1}) // [undefined, undefined] m2({x: 1}) // [1, undefined]

Your first syntax (m1({x = 0, y = 0} = {})) does three things:

  • First, it provides a default first argument to the function, which is an empty object. If no first argument is given (m1()) then the default empty object is used (i.e. it becomes m1({}))
  • Second, your code extracts the x and y properties from that object.
  • If either is undefined, it is given a default value 0.

m2({x, y} = { x: 0, y: 0 }) does something quite different:

  • First it provides a default first parameter to the function, which is the object {x: 0, y: 0}. If no first argument is passed, that object is used. If any argument other than undefined is passed, that value is used instead.
  • Second, the code extracts the x and y properties from that object. If they are undefined, that's what you'll get.

The first option (a parameter with a default value that is destructured with more default values) is almost certainly what you want. The second option means that your code does not have sensible/useful default values for the property if arguments are passed.

更多推荐

功能的JavaScript默认参数

本文发布于:2023-06-02 19:31:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/457419.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   功能   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!