簡體   English   中英

nodejs打印數組元素,除了第一個索引

[英]nodejs print array elements all except first index

在NodeJS(最新)中,我可以打印

console.log(args[0])
console.log(args[1])
console.log(args[2])

就我而言,我打印這些參數索引變量的函數是使用NodeJS child.spawn(command,args)方式,即用戶可以傳遞1、2或5或N no。 論據。 由於我不知道可以設置多少用戶,因此無法為N否編寫console.log()行。 各個索引。

如何打印除索引args [0]以外的所有參數?

索引args [1]包含我可以打印的命令名稱。 索引args [2]開始,可能包含args [2] =“ -c”,args [3] =“ param1”,args [4] =“ paramX paramY”等,依用戶將參數推入args的方式而定調用打印console.log行的函數之前,請在.js文件中使用數組。

我想打印輸出,如:args [0] = / usr / bin / bash args [XXX] = -c,param1,param2,param3 param4,param5等,等等

如果我理解正確,那么您正在尋找以下方面的東西:

 // wrap in function to mimic the arguments object function execute() { // declare a place to store the arguments var result = [] // iterate through each argument Array.from(arguments).forEach((value, key) => { // skip the second key if (key > 0) { // store each argument in the result array result.push(value) } }) // console log the result array as multiple arguments console.log.apply(null, result) // -> /usr/bin/bash -c param1 param2 param3 } // mock command execute('/usr/bin/bash', 'command', '-c', 'param1', 'param2', 'param3') 

我希望這有幫助!

正如我在評論中所說,您可能想要這樣的東西。

 function func(...args){ args.forEach((el, i)=>i != 1 && console.log(el)); }; func('/usr/bin/bash', 'Something not used', '-c', 'param1', 'param2', 'param3'); 

如果您使用arguments變量:

 function func(){ // Equivalent to [...arguments] Array.from(arguments).forEach((el, i)=>i != 1 && console.log(el)); }; func('/usr/bin/bash', 'Something not used', '-c', 'param1', 'param2', 'param3'); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM