参数可以用作默认值吗?

时间:2020-09-09 07:58:47

标签: javascript

您可以使用先前定义的参数来默认其他参数吗?

我有一个具有更新功能的对象,它将更新列表中的一项。 因此,我将数据对象传递给函数,并且指定的对象将被更新。

class Device {
    constructor() {
        this.systems = [new System()];
        // ...
    }

    update(data, index) {
        this.systems[index].update(data);
    }
}

但是我想用可选的索引来称呼它。意味着将data.index属性分配为默认值。

否:new Device().update(data, data.index);

3 个答案:

答案 0 :(得分:1)

您想要index对象中的data,类似这样:

function test({ index = 42, ...data } = {}) {
  console.log(index, data);
}

test();
test({ hello: 'world' });
test({ index: 100, a: 'b' });

答案 1 :(得分:0)

它确实可以工作,但是我不确定是否应该使用它。

function test(a, b = a) {
    return a + b;
}

仅使用一个参数b调用函数时,将设置为a

test(2);将返回4,而test(2, 3);将返回5

当然,这不会相反。

function test2(a = b, a) {
    return a + b;
}

致电test2(undefined, 2);会抛出Uncaught ReferenceError: Cannot access 'b' before initialization,这是预期的。

用作默认值的参数必须在更早的时候指定。

答案 2 :(得分:0)

您可以直接将此作为参数:

function multiply(a, b = a) {
  return a * b;
}

或检查未定义的

function multiply(a, b) {
  b = (typeof b !== 'undefined') ?  b : a;
  return a * b;
}

取决于是否要直接将其作为参数或在方法主体中使用。

看看:https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Default_parameters