将未设置的属性设置为函数中的默认属性? [英] setting unset properties as default properties in a function?

查看:61
本文介绍了将未设置的属性设置为函数中的默认属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JS的新手,我正在尝试学习函数的一些基础知识.
我遇到了一个问题,我创建了一个像这样的函数:

I'm pretty new to JS and i'm trying to learn some basics in functions.
I'm facing a problem, I've created a function like this:

function someName (element, settings={i:"#1d252c", i2:"#fff"}) {
    .......
}

如果我将函数称为someName(element). i和i2保留其值,但是

If i call the function as someName(element). i and i2 retain their values, however

如果我像someName(element,{i:"#3acbda"})这样称呼它,i的值的确发生了变化,但是i2的值未定义,

If i call it like someName(element,{i:"#3acbda"}), the value of i does change however the value of i2 is undefined,

当设置对象不再是默认值时,如何为属性分配默认值.
因此,当我仅分配给i的设置时,i2只是默认值"#fff"而不是未定义.

So how do i assign the default value to a property when the settings object is no longer the default value.
So when i assign settings with only i, i2 is just the default value "#fff" and not undefined.

推荐答案

您可以使用对象散布运算符 ...使用默认设置丰富您的选项

You could use the Object spread operator ... to enrich your options with default settings

function someName(element, options){
    const settings = {i:"#aaa", i2:"#fff", ...options};
    console.log(settings)
}

// let's test
someName(null, {i:"#000"});

这是我的首选.另外,您也可以使用第三个参数:

which is my preferred. Alternatively you could also use a third argument:

function someName(element, options, settings={i:"#aaa", i2:"#fff", ...options}){
    console.log(settings)
}

// let's test
someName(null, {i:"#000"});

如果您不想这样做,或者发现总是需要使用settings对象引用(例如settings.isettings.i2等),可以使用对象解包 -并直接输入propertyName:

In case you don't want to, or find clumbersome to always have to use the settings Object reference (like settings.i, settings.i2 etc), you can use Object unpacking - and go directly for the propertyName:

function someName(element, options ){
    const {i="#aaa", i2="#fff"} = options; 
    console.log( i, i2 );
}

// let's test
someName(null, {i:"#000"});

这篇关于将未设置的属性设置为函数中的默认属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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