Javascript对象解构和默认参数组合 [英] Javascript Object destructuring and default parameters combined

查看:31
本文介绍了Javascript对象解构和默认参数组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我遇到了以下我不认识的语法:

Today I came across the following syntax which I didn't recognize:

const createUser = ({
  age = 1,
  name = 'Anonymous',
}) => ({
  age,
  name,
});


const defaultP = createUser({
  age: 5
});
console.log(defaultP);

我认为它使用对象解构和默认参数来设置作为参数发送的对象的默认值.

I think it uses Object destructuring and default parameters in order to set defaults of the object which is send as an argument.

语法让我有些不安,因为通常我只能以以下方式看到对象的分解:

The syntax threw me a bit off because normally I see object destructuring only in the following manner:

let obj = {
   prop1: 1
}

const {prop1} = obj;

console.log(prop1);

此语法如何正确工作?

推荐答案

该语法确实使用了 Mozilla文档中有一些示例a>有助于我们理解窍门的方法,请查看以下内容:

That syntax indeed uses Object Destructuring in order to extract default values from the parameter object. There are some examples in the Mozilla documentation that helps us understand the trick, check this out:

var {a = 10, b = 5} = {a: 3};
console.log(a); // 3
console.log(b); // 5

该示例的一个可能的缺点是, createUser 方法将忽略参数对象的所有其他值,并且始终返回仅包含 age 的对象.code>和 name .如果您想使其更加灵活,我们可以像这样使用 Object.assign():

A possible disadvantage of your example is that the createUser method ignores all other values of the parameter object and always returns an object that contains only age and name. If you want to make this more flexible, we could use Object.assign() like this:

const createUser = (o) => Object.assign({ age: 1, name: 'Anonymous' }, o);

在这种情况下,创建的用户将是一个将参数对象与默认值合并的对象.现在注意,默认值在方法主体中.使用这种方法,我们可以创建包含其他属性的用户,例如:

In this case, the user created will be an object that merges the parameter object with the default values. Note now that the default values are in the method body. With this method we can create users that contain other properties, example:

const superman = createUser({ name: 'Superman', type: 'superhero' });
console.log(superman);
// output: {age: 1, name: "Superman", type: "Superhero"}

这篇关于Javascript对象解构和默认参数组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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