2017-07-28 93 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);