仅在javascript中传递第二个参数

Web*_*man 6 javascript arguments function

我目前正在尝试制作一个仅传递函数第二个参数的函数。我已经阅读了一些文档,但没有任何探索。

我会做到的:

 function test (a,b){ ....};
    // pass only the second parameter 
    test( ... , b) ;
Run Code Online (Sandbox Code Playgroud)

我当前的想法是将第二个参数作为实际的动态默认参数传递,如下所示:

    var defaultVar = "something" ;

    function test (a,b = defaultVar){...}
Run Code Online (Sandbox Code Playgroud)

然后根据我的需要更改defaultVar值。

var defaultVar = modification ; 
Run Code Online (Sandbox Code Playgroud)

实际上,我正在使用Google驱动器API,并且尝试在第二个参数中输入字符串值以进行回调。此回调将充当验证返回文件是否有效的搜索文件的角色(通​​过对名称值进行布尔验证)。

因此,我的想法是通过传递他的名字并以此方式检索文件数据来自动化在Google驱动器上获取文件的过程。

我希望我的精确度会有所帮助。

这是我的quickstart.js:

(...Google authentication and all) ; 

 var filename = "";
// enter a filename in the function by the way of filename
function listFiles (auth, filename =  filename) {
  const drive = google.drive({version: 'v3', auth});
  drive.files.list({
    pageSize: 50,
    fields: 'nextPageToken, files(id, name)',
  }, (err, {data}) => {
    if (err) return console.log('The API returned an error: ' + err);
    const files = data.files;
    if (files.length) {
      console.log('Files:');
      files.map((file) => {
        console.log(`${file.name} (${file.id})`);

            // check if the file returns match the filename wished 
            displayFile(file);
              if(`${file.name}` == filename ){
                console.log("name found !")
                      const fileData = { name : `${file.name}`,
                                         id : `${file.id}`
                      }
         return fileData
        }

      });
    } else {
      console.log('No files found.');
    }
  });
}

listFiles(undefined, "test.md")
Run Code Online (Sandbox Code Playgroud)

任何改进的想法显然都是受欢迎的,

谢谢

tri*_*cot 13

如果您可以更改函数采用的参数数量,则可以通过对象属性传递参数。然后您可以让调用者决定在调用期间指定哪个(或多个)属性。

其他属性可以通过函数参数规范中的对象解构来采用默认值:

function test({a = 1, b = 2}) {
    console.log(`a = ${a}, b = ${b}`);
};

test({b:42}); // only specify what b is
Run Code Online (Sandbox Code Playgroud)

  • 惊人的答案!您的答案应该被接受! (3认同)

T.J*_*der 10

随着默认参数值在ES2015加入,可以为参数声明默认值,请在致电时,如果传递undefined的第一个参数,它会得到默认:

function test(a = "ay", b = "bee") {
  console.log(`a = ${a}, b = ${b}`);
}
test();             // "a = ay, b = bee"
test(1);            // "a = 1, b = bee"
test(undefined, 2); // "a = ay, b = 2"
test(1, 2);         // "a = 1, b = 2"
Run Code Online (Sandbox Code Playgroud)

您可以在ES2015之前的环境中通过测试以下各项来手动执行类似的操作undefined

function test(a, b) {
  if (a === undefined) {
    a = "ay";
  }
  if (b === undefined) {
    b = "bee";
  }
  console.log("a = " + a + ", b = " + b);
}
test();             // "a = ay, b = bee"
test(1);            // "a = 1, b = bee"
test(undefined, 2); // "a = ay, b = 2"
test(1, 2);         // "a = 1, b = 2"
Run Code Online (Sandbox Code Playgroud)