如何使用嵌套对象作为函数参数?

时间:2018-09-11 14:58:08

标签: javascript

以下示例正在工作:

const data1 = {
  first: 1,
  second: 2
};

const data2 = {
  first: 'first',
  second: 'second'
};

function test(obj) {
  console.log(obj.first, obj.second);
}

test(data1); // 1 2
test(data2); // first second

当data1和data2作为另一个对象中的嵌套对象时该怎么办?

const data = {
  data1: {
        first: 1,
        second: 2
 },
 data2: {
        first: 'first',
       second: 'second'
 }
}

1 个答案:

答案 0 :(得分:0)

您可以将嵌套对象作为参数传递给test函数:

const data = {
  data1: {
    first: 1,
    second: 2
  },
  data2: {
    first: 'first',
    second: 'second'
  }
};

function test(obj) {
  console.log(obj.first, obj.second);
}

test(data.data1); // 1 2
test(data.data2); // first second
相关问题