如何将对象的属性作为参数传递给函数

时间:2020-10-21 19:40:38

标签: javascript jquery

我想将对象发送到函数,其属性等于预期的参数。

这是一个代码示例:

function fun(a, b, c){
    console.log('a='+a, 'b='+b, 'c='+c);
}

obj = {a:'1', b:'2', c:'3'};

fun(obj); //a=1 b=2 c=3

在python中,我会= fun(obj**)

4 个答案:

答案 0 :(得分:1)

在ES6中,您可以简单地执行以下操作:

function fun(payload) {
   const {a = 'backup', b, c} = payload // assign a default argument for a if it is not available in the argument.
   console.log('a='+a, 'b='+b, 'c='+c)
}

obj = {a:'1', b:'2', c:'3'}

fun(obj) //a=1 b=2 c=3

这利用了对象重组的优势,这使得可以将数组中的值或对象中的属性解压缩为不同的变量。在这种情况下,它将解压缩要在函数内部使用的变量a, b, c

在此了解有关MDN的更多信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

答案 1 :(得分:0)

您可以使用对象分解

function fun({a, b, c}) {
  console.log("a=" + a, "b=" + b, "c=" + c);
}

obj = { a: "1", b: "2", c: "3" };

fun(obj); //a=1 b=2 c=3

答案 2 :(得分:0)

有两种方法。

1使用点运算符作为大括号,使对象成为对象文字。

function fun(obj){
    console.log('a='+obj.a, 'b='+obj.b, 'c='+obj.c);
}
obj = {a:'1', b:'2', c:'3'};
fun(obj); //a=1 b=2 c=3

2使用ES6解构(通过这种方式,您可以轻松地分配默认值,以防对象没有像-1这样的字段)

function fun(obj){
    const {a = -1, b=-1, c=-1} = obj;
    console.log('a='+a, 'b='+b, 'c='+c);
}
obj = {a:'1', b:'2', c:'3'};
fun(obj); //a=1 b=2 c=3

答案 3 :(得分:0)

使用对象分解来完成此操作

abstract class AbstractDataService {}

@Inject()
class DataService extends AbstractDataService {}

@Inject()
class MockDataService extends AbstractDataService {}

@Component({
  selector: 'app-root'
  template: '<app-parent></app-parent>'
})
class AppComponent implements OnInit {
  constructor(private router: Router) { }

  ngOnInit() {
    this.router.events.subscribe((evt: NavigationStart) => {
      if (evt.url === '/demo') { // something like that or do it in router config...
        // TODO change the injection instance here for ParentComponent and children...
      }
    });
  }
}

@Component({
  selector: 'app-parent',
  template: '<app-child1></app-child1> <app-child2></app-child2>'
})
class ParentComponent {
  constructor(private data: AbstractDataService) { }
  // ...
}


@Component({...})
class Child1Component {
  constructor(private data: AbstractDataService) { }
  // ...
}


@Component({...})
class Child2Component {
  constructor(private data: AbstractDataService) { }
  // ...
}