在 javascript 中调用带有数组循环的函数

Invoke a function with a loop of arrays in javascript

我有这个 node.js 代码:

var timeStamp = function() {
  var d = new Date();
  var year = d.getFullYear();
  var month = d.getMonth() + 1;
  var day = d.getDay();
  var hours = d.getHours();
  var minutes = d.getMinutes();
  var seconds = d.getSeconds();
  var milliseconds = d.getMilliseconds();
  var time = year + '.' + month + '.' + day + '. ' + hours + ':' + minutes + ':' + seconds + ':' + milliseconds;
  return time;
};

var tld = function() {
  var domainExtensions = ['.com', '.org'];

  for (var i=0; i<domainExtensions.length; i++) {
  return domainExtensions[i];
  }
};

// print process.argv
process.argv.forEach(function(val, index, array) {
  console.log(index + ': ' + val + '' + tld() + ' █ ' + timeStamp());
});

这次输出:

$ node index.js one two=three four
0: C:\Program Files\nodejs\node.exe.com █ 2015.11.5. 13:45:18:187
1: c:\www\node\command-line-arguments\index.js.com █ 2015.11.5. 13:45:18:191
2: one.com █ 2015.11.5. 13:45:18:192
3: two=three.com █ 2015.11.5. 13:45:18:192
4: four.com █ 2015.11.5. 13:45:18:193

然而我想要的是在控制台中打印一个控制台参数与数组的每个循环:

$ node index.js one two=three four
0: C:\Program Files\nodejs\node.exe.com █ 2015.11.5. 13:45:18:187
1: C:\Program Files\nodejs\node.exe.hu █ 2015.11.5. 13:45:18:187
2: c:\www\node\command-line-arguments\index.js.com █ 2015.11.5. 13:45:18:191
3: c:\www\node\command-line-arguments\index.js.hu █ 2015.11.5. 13:45:18:191
4: one.com █ 2015.11.5. 13:45:18:192
5: one.hu █ 2015.11.5. 13:45:18:192
6: two=three.com █ 2015.11.5. 13:45:18:192
7: two=three.hu █ 2015.11.5. 13:45:18:192
8: four.com █ 2015.11.5. 13:45:18:193
9: four.hu █ 2015.11.5. 13:45:18:193

有办法实现吗?

感谢您的帮助!

当您调用 return 时您离开了循环。 tld 函数总是 return ".com".

试试这个

var timeStamp = function() {
  var d = new Date();
  var year = d.getFullYear();
  var month = d.getMonth() + 1;
  var day = d.getDay();
  var hours = d.getHours();
  var minutes = d.getMinutes();
  var seconds = d.getSeconds();
  var milliseconds = d.getMilliseconds();
  var time = year + '.' + month + '.' + day + '. ' + hours + ':' + minutes + ':' + seconds + ':' + milliseconds;
  return time;
};

//better to be const
var domainExtensions = ['.com', '.org'];

// print process.argv
process.argv.forEach(function(val, index, array) {
  domainExtentions.forEach(function(tld) {
     console.log(index + ': ' + val + '' + tld + ' █ ' + timeStamp());
  });

});