2017-07-28 96 views
0

我遇到了一个相当烦人的小句法问题。我目前使用剪刀节点模块来处理PDF文件。Concat String to Int

选购一些PDF文件的网页的语法在文档中描述:

var scissors = require('scissors'); 
var pdf = scissors('in.pdf') 
    .pages(4, 5, 6, 1, 12) 

这实际上对我的作品不错,但我希望动态做到这一点。我将如何将整数连接到JavaScript中的逗号?如果我传递一个字符串,该函数不再工作。

非常感谢

+0

还有的[ES6传播语法(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator) –

回答

2

您将n个值作为参数传递给一个函数。如果将它连接成一个字符串,则只会传递一个参数,即连接的字符串。

也许你想如果你有号码使用蔓延运营商https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator

成你想要将它们传递给这样的功能的阵列:

var scissors = require('scissors'); 
var pages = [4, 5, 6, 1, 12]; 
var pdf = scissors('in.pdf') 
    .pages(...pages); 
+0

哇,我从来没有见过这个。工作很好 –

2

您可以使用功能。 prototype.apply为此。

var scissors = require('scissors'); 
var pdf = scissors('in.pdf'), 
    args = [4, 5, 6, 1, 12]; 

scissors.pages.apply(pdf, args); 
+0

谢谢,正是我所期待的 –

0

我假设你的意思是你想传递一个参数数组到页面函数。你可以做到这一点的JavaScript的apply function

var scissors = require('scissors'); 
var pdf = scissors('in.pdf') 

pdf.pages.apply(pdf, [4, 5, 6, 1, 12]) 
1

你应该能够页码的数组传递给函数。 我接过一看scissors source code,他们似乎采取实际的参数自理:

/** 
* Creates a copy of the pages with the given numbers 
* @param {(...Number|Array)} Page number, either as an array or as  arguments 
* @return {Command} A chainable Command instance 
*/ 
Command.prototype.pages = function() { 
    var args = (Array.isArray(arguments[0])) ? 
    arguments[0] : Array.prototype.slice.call(arguments); 
    var cmd = this._copy(); 
    return cmd._push([ 
    'pdftk', cmd._input(), 
    'cat'].concat(args.map(Number), [ 
     'output', '-' 
     ])); 
}; 

您可以通过将被组合成阵列Array.prototype.slice多个参数或只是通过将用于数组直。

var scissors = require('scissors'); 

var pages = []; 

/* collect desired pages */ 
pages.push(23); 
pages.push(42); 
pages.push(1337); 

var pdf = scissors('in.pdf').pages(pages);