需要JavaScript函数的参数

JavaScript is notorious for being "loose", something that some developers love but other developers loathe.  I hear most of those complaints from server side developers, who want string typing and syntax.  While I like strict coding standards, I also like that JavaScript lets me quickly prototype without having to cross the I's and dot the T's.  Until recently you couldn't define default parameter values for functions in JavaScript, but now you can!

JavaScript因其“松散”而臭名昭著,有些开发人员喜欢它,而其他开发人员则讨厌。 我听到来自服务器端开发人员的大多数抱怨,他们想要字符串输入和语法。 虽然我喜欢严格的编码标准,但我也喜欢JavaScript,它使我可以快速制作原型,而不必跨越I和加点T。 直到最近,您还无法为JavaScript中的函数定义默认参数值,但是现在您可以了!

When I posted last week about Six Tiny but Awesome ES6 Features, an awesome reader (cmwd) pointed out that you can not only set default function parameter values but you can throw errors when a given parameter isn't provided to a function:

当我上周发布有关“ 六种小巧但很棒的ES6功能”时 ,一位很棒的读者( cmwd )指出,您不仅可以设置默认的函数参数值,而且在未向函数提供给定参数时也可能引发错误:


const isRequired = () => { throw new Error('param is required'); };

const hello = (name = isRequired()) => { console.log(`hello ${name}`) };

// This will throw an error because no name is provided
hello();

// This will also throw an error
hello(undefined);

// These are good!
hello(null);
hello('David');


I love this tip -- it shows how with each addition to JavaScript we can stretch the language to do interesting things.  How practical it is to throw errors in production is up to you but this is an awesome ability during development.  Happy coding!

我喜欢这个技巧-它显示了JavaScript的每一项添加如何使我们能够扩展语言以执行有趣的事情。 在生产中引发错误的实际程度取决于您,但这是开发过程中的出色能力。 编码愉快!

翻译自: https://davidwalsh.name/javascript-function-parameters

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值