将此`for循环'设为函数

时间:2017-04-20 05:39:20

标签: javascript

本准则阅读&发送JSON文件文件
如何将此代码设为功能并将其调用为1行?

  //  sendAllDocument
  var i,j,tempstring;
  for (i=0,j=locale.keyboards[msg.text].document.length; i<j; i++) {
      tempstring = locale.keyboards[msg.text].document[i];
      bot.sendDocument(msg.chat.id, tempstring, opts);
  }

3 个答案:

答案 0 :(得分:4)

function sendAllDocument(msg, opts) {
    var i,j,tempstring;
    for (i=0,j=locale.keyboards[msg.text].document.length; i<j; i++) {
        tempstring = locale.keyboards[msg.text].document[i];
        bot.sendDocument(msg.chat.id, tempstring, opts);
    }
}

致电:

sendAllDocument(msg, opts);

答案 1 :(得分:2)

function sendAllDocument(){
  var i,j,tempstring;
  for (i=0,j=locale.keyboards[msg.text].document.length; i<j; i++) {
      tempstring = locale.keyboards[msg.text].document[i];
      bot.sendDocument(msg.chat.id, tempstring, opts);
  }
}

并将其称为sendAllDocument()

答案 2 :(得分:0)

创建一个函数:

function sendAll(msg, opts, bot) {
    locale.keyboards[msg.text].document.forEach(function (document) {
        bot.sendDocument(msg.chat.id, document, opts);
    };
};

并执行它:

sendAll(msg, opts, bot);