首页 > 解决方案 > 在 JavaScript 中,您可以通过哪些方式将参数传递给函数?

问题描述

从 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)?

标签: javascriptsyntax

解决方案


看来您真正要问的不是 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"); 


推荐阅读