【发布时间】:2016-02-17 07:40:44
【问题描述】:
我正在尝试在 Node.js 中实现原始命令行参数。
当我实现简单的变量时,一切正常
(node example.js variable)
但是当我将数组作为参数实现时,它不起作用
(node example.js "['127.0.0.5', '127.0.0.3']" )
完整代码:
if (process.argv.length <= 3) {
console.log("Usage: " + __filename + " SOME_PARAM");
process.exit(-1);
}
var variable = process.argv[2];
var array = process.argv[3];
console.log('Host: ' + variable);
console.log('array: ' + array);
问题
参数输入示例(node example.js variable "['127.0.0.5', '127.0.0.3']")
如何将第二个参数 ("['127.0.0.5', '127.0.0.3']") 作为数组而不是字符串(现在这样)传递,以便稍后我可以访问数组的第 n 个元素(例如 array[0] = '127.0.0.5')
解决方案
输入应该类似于('["127.0.0.5", "127.0.0.3"]' 更改引号),我们还需要将参数解析为 JSON。
if (process.argv.length <= 3) {
console.log("Usage: " + __filename + " SOME_PARAM");
process.exit(-1);
}
var variable = process.argv[2];
var array = JSON.parse(process.argv[4]);
console.log('Host: ' + variable);
console.log('array: ' + array);
console.log(array[1]
【问题讨论】:
-
您不能“将其作为数组传递”,但您可以解析参数来构建您的数组。无论如何,您都会得到一个字符串,由您将其转换为数组。
标签: javascript arrays node.js arguments