我正在尝试制作一个函数,其中我只传递函数的 第二个 参数。
我希望它以这种方式工作:
function test (a,b) {
// ...
};
// pass only the second parameter
test( ... , b);
我目前的想法是将第二个参数作为 事实上的 动态默认参数传递,如下所示:
var defaultVar = "something";
function test (a, b=defaultVar) {
// ...
}
…然后根据我的需要更改 defaultVar
值。
var defaultVar = modification;
事实上,我正在使用 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")
欢迎任何改进的想法。
原文由 Webwoman 发布,翻译遵循 CC BY-SA 4.0 许可协议
ES2015增加了 _默认参数值_,可以为参数声明默认值,调用时,如果传入
undefined
作为第一个参数,会得到默认值:您可以通过测试
undefined
在 ES2015 之前的环境中手动执行类似操作: