在javascript函数定义中的对象 [英] object in javascript function definition

查看:100
本文介绍了在javascript函数定义中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的朋友只是做了一些无意义的代码,或者至少我认为他是,但令我惊讶的是它并没有抛出任何错误。但是他没有做到他所期望的,因为他并不知道自己在做什么。
但是现在我很好奇它做了什么,因为肯定有一些理由不会抛出错误。
代码看起来像这样:

My friend was just making some nonesense code, or atleast I thought he was, but to my surprise it did not throw any error. It however did not do what he expected, as he didn't really know what he was doing. But now I am quite curious what it does do, because there must be some reason it doesn't throw an error. The code looked something like this:

var n = function(someArg, anotherArg, {help: []}){};

另外,向对象中添加数据时,会引发错误:

Also, when adding data into the object, it throws an error:

var n = function(someArg, anotherArg, {help: ["something"]}){};

抛出:'Uncaught SyntaxError:意外的字符串'

Throws: 'Uncaught SyntaxError: Unexpected string'

那么为什么是一个随机的参数呢?

so why is a random argument allowed?

推荐答案

这是EcmaScript 6 参数解构。如果你定义一个函数为:

This is EcmaScript 6 argument destructuring. If you define a function as:

function myfun({help: [a, b, c]}) {}

然后您可以将其称为:

You can then call it as:

myFun({help: [1, 2, 3]});

,它将绑定参数 a b c 1 2 3 。你的例子只是一个简单的例子,其中包含变量的数组是空的。

and it will bind the arguments a, b, and c to 1, 2, and 3 respectively. Your example is simply a degenerate case of this, where the array containing the variables is empty.

在解构参数列表中,表达式可以放在普通对象中的位置或数组文字必须包含变量名称,因为这是将绑定到参数对象/数组中相应元素的变量。这就是为什么第二个版本产生错误的原因:something不是变量名称,它是一个字符串,所以它不能用于模式。

In a destructuring argument list, the places where expressions can go in an ordinary object or array literal have to contain a variable name, as that's the variable that will be bound to the corresponding element in the argument object/array. This is why the second version produced an error: "something" is not a variable name, it's a string, so it can't be used in a pattern.

这篇关于在javascript函数定义中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆