gpt4 book ai didi

javascript - ES6 - 默认参数结合解构 : What does this pattern mean?

转载 作者:行者123 更新时间:2023-11-30 11:50:45 25 4
gpt4 key购买 nike

我在 CodeReview 问题中看到了这些模式:

toggleModal({title = null, description = null, cancelLabel = 'No', submitLabel = 'Yes'} = {}) {
this.setState({
modalVisible: !this.state.modalVisible,
title: title,
description: description,
cancelLabel: cancelLabel,
submitLabel: submitLabel
});
},

完整的帖子: https://codereview.stackexchange.com/questions/141699/react-modal-visibility-and-content-toggling-based-on-action-clicked

我会说它是 ES6 Default Parameter 和 Destructing 的组合。

试图理解其目的。但还是没主意。

为什么不单独使用默认参数?

谁能给我解释一下这个模式是关于什么的?

最佳答案

I would say it's a combination of ES6 Default Parameter with Destructuring.

在 JavaScript 中,我们称它们为“参数”,而不是参数,但没错,就是这样。它分为三个部分。让我们逐个构建它:

  1. 解构。在函数中,我们想使用titledescription等作为局部变量,所以我们声明解构参数:

    // Just the destructuring
    toggleModal({title, description, cancelLabel, submitLabel}) {
  2. 我们希望这些单独的属性具有默认值,因此我们为它们分配默认值:

    // Add in defaults for the props
    toggleModal({title = null, description = null, cancelLabel = 'No', submitLabel = 'Yes'}) {
    // ---------------^^^^^^^-------------^^^^^^^-------------^^^^^^^-------------^^^^^^^^
  3. 我们还想使整个对象成为可选的,所以我们为对象分配了一个默认值:

    // Add in a default for the object as a whole
    toggleModal({title = null, description = null, cancelLabel = 'No', submitLabel = 'Yes'} = {}) {
    // ------------------------------------------------------------------------------------^^^^^

所以这样:

toggleModal();

例如,没有参数,做同样的事情:

toggleModal({});

...因为整体默认值(上面的#3)启动,它做同样的事情:

toggleModal({title: null, description: null, cancelLabel: 'No', submitLabel: 'Yes'});

...因为个人默认值(上面的#2)开始了。

因为参数是解构的,所以函数可以在主体中使用titledescription 等(上面#1)。

这是一个更简单的例子:

// REQUIRES ES2015+ SUPPORT IN YOUR BROWSER
function adams({answer = 42, question = "Life, the Universe, and Everything"} = {}) {
console.log("Answer: " + answer);
console.log("Question: " + question);
}

adams();
console.log("--");
adams({answer: 67});
console.log("--");
adams({question: "The mice are revolting!"});
console.log("--");
adams({
question: "Would you like a piece of cake?",
answer: "Yes, please!"
});

输出:

Answer: 42Question: Life, the Universe, and Everything--Answer: 67Question: Life, the Universe, and Everything--Answer: 42Question: The mice are revolting!--Answer: Yes, please!Question: Would you like a piece of cake?

关于javascript - ES6 - 默认参数结合解构 : What does this pattern mean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39566798/

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