gpt4 book ai didi

javascript - 有人可以向我解释一下这个 : 'create({email: emailArg} = {}) {}' ?

转载 作者:搜寻专家 更新时间:2023-11-01 00:27:14 25 4
gpt4 key购买 nike

我还在学习 JS。做 Apollo GraphQL 教程:https://www.apollographql.com/docs/tutorial/introduction/

我不太明白这部分:findOrCreateUser({ email: emailArg } = {})

完整代码如下:

   /**
* User can be called with an argument that includes email, but it doesn't
* have to be. If the user is already on the context, it will use that user
* instead
*/
async findOrCreateUser({ email: emailArg } = {}) {
const email =
this.context && this.context.user ? this.context.user.email : emailArg;
if (!email || !isEmail.validate(email)) return null;

const users = await this.store.users.findOrCreate({ where: { email } });
return users && users[0] ? users[0] : null;
}

async bookTrips({ launchIds }) {
const userId = this.context.user.id;
if (!userId) return;

let results = [];

// for each launch id, try to book the trip and add it to the results array
// if successful
for (const launchId of launchIds) {
const res = await this.bookTrip({ launchId });
if (res) results.push(res);
}

return results;
}

请教育我或解释的链接就可以了。谢谢。

最佳答案

findOrCreateUser({ email: emailArg } = {})

是几个原则的结合

1) 对象解构

const { prop } = obj;

相当于:

const prop = obj.prop;

2) 函数参数解构

同样的事情,但对于函数的参数

function fun({ prop }) {
console.log(prop);
}

相当于

function fun(obj) {
console.log(obj.prop);
}

3) 解构时重命名变量

function fun({ prop: newPropName }) {
console.log(newPropName);
}

相当于

function fun(obj) {
const newPropName = obj.prop;
console.log(newPropName);
}

4)默认函数参数

function fun(arg = 5) {
console.log(arg);
}

fun(10); // prints 10
fun(); // prints 5 since no value was passed to fun

结论:

findOrCreateUser({ email: emailArg } = {}) {
// [...]
}

相当于

findOrCreateUser(args) {
const emailArg = args ? args.email : {};
// [...]
}

换句话说,它将传递给方法的对象的 email 属性重命名为 emailArg 并使其直接可用。如果没有向函数传递任何内容,它还会将参数初始化为一个空对象。这是为了避免在未传递任何内容时引发 Cannot read email of undefined

如果您需要更多上下文,这里是文档:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Assigning_to_new_variable_names

关于javascript - 有人可以向我解释一下这个 : 'create({email: emailArg} = {}) {}' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57107654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com