您可以通过什么方式将参数传递给JavaScript中的函数?

问题描述 投票:1回答:1

从Python进入一些基于JavaScript的API,我对某些语法感到困惑。而且我找不到有关声明函数的所有随机信息的答案。

在Python中,您可以根据顺序和名称将指定参数混合到函数中:np.arange(1,5,step = 5)

您能用Javascript做类似的事情吗?

如果有类似的功能:ee.List.sequence(start,end, step, count)它只需要四个参数中的三个即可,我真的可以轻松地指定开始,结束,步骤,如下所示:ee.List.sequence(1,100,2)

但是,我必须使用对象符号来指定计数吗?ee.List.sequence({start=1,end=100, count=50})

是否有速记,例如在Python中,例如:ee.List.sequence(1,100,{count=50})要么ee.List.sequence(1,100,,50)

javascript syntax
1个回答
0
投票

似乎您真正要问的不是关于JavaScript作为一种语言,而是关于特定的API。所以,这里有一些事情要知道:

在JavaScript中,所有参数都是可选的。换句话说,没有办法强制使用适当数量或顺序的参数来调用函数。取决于调用方的函数签名,并适当地调用它,这取决于调用方。函数的创建者还需要为不传递某些或所有参数做好准备。所有函数都具有一个arguments类似数组的对象,可以帮助实现这一点,但是检查输入也非常容易。这是一个例子:

// Here's an example of a function that does not explicitly declare any arguments
function foo1(){
  // However, arguments might still be passed and they can be accessed 
  // through the arguments object:
  console.log("Arguments.length = ", arguments.length);
  console.log(arguments);
}

foo1("test", "boo!"); // Call the function and pass args even though it doesn't want any

// ***********************************************

// Here's an example of a function that needs the first arg to work,
// but the seond one is optional
function foo2(x, y){
  if(y){
    console.log(x + y);
  } else {
    console.log(x);
  }
}

foo2(3);
foo2(4, 5); 

在JavaScript中,您的函数可以采用任何有效的原语或对象。同样,由调用者决定API是什么并正确调用它:

function foo1(string1, number1, object1, string2){
  console.log(arguments);
}

foo1("test", 3.14, {val:"John Doe"}, "ing"); 
© www.soinside.com 2019 - 2024. All rights reserved.