我最近开始学习Node.js,我想知道如何让一个函数接受数组形式的多个字符串。例如,
export default (config: Config) => {
return {
target: 'https://google.com',
endpoint: null,
tick: 500,
verbose: true,
once: false,
}
}
因此,我想要的不是target: "https://google.com"
,而是target: ['https://google.com', 'https://facebook.com']
。我可能会缺少一些东西,但是我对如何执行此操作有些迷失。
答案 0 :(得分:1)
您可以使用rest parameters。语法是
const hello = (...args) => {
// args is now an array
console.log(args)
}
然后您可以像这样使用它:
hello('This ', 'is ', 'an ', 'example') // outputs ['This ', 'is ', 'an ', 'example']
您可以在其中传递任意数量的参数。
所以回到您的示例,您可能会喜欢
const example = (...targets) => {
return {
target: targets,
endpoint: null,
tick: 500,
verbose: true,
once: false,
}
}
module.exports = example
您可以像这样使用它
const example = require('./example')
let val = example('google', 'twitter', 'yahoo')
console.log(val)
Rest参数应该是函数中的最后一个参数。因此,如果您想传递其他一些参数,则语法为
function hello(param, ...rest) {
// rest is an array
...
}
您还可以直接传递数组或引用数组的变量:
function hello(param) {
...
console.log(param)
}
hello(["hello", "world"]) // outputs ["hello", "world"]
or
var arr = ["hello", "world"]
hello(arr)
您还可以了解有关Array-like object arguments here
的更多信息