2016-07-27 60 views
1

我正在用Angular2創建一個應用程序,並且我有一組派對。如何分離Typescript中的數組

const PARTIES: Party[] = [ 
    { id: 1, title: "Main Event", description: "The biggest, most extravagant event in the last 10,000,000 years." }, 
    { id: 2, title: "Secondary Event", description: "The not as biggest, less extravagant event in the last 10,000,000 years." }, 
    { id: 3, title: "Another Event", description: "N/A" }, 
    { id: 4, title: "Another Event", description: "N/A" }, 
    { id: 5, title: "Another Event", description: "N/A" }, 
    { id: 6, title: "Another Event", description: "N/A" }, 
    { id: 7, title: "Another Event", description: "N/A" }, 
    { id: 8, title: "Another Event", description: "N/A" }, 
    { id: 9, title: "Another Event", description: "N/A" }, 
    { id: 10, title: "Another Event", description: "N/A" } 
]; 

同時保留原始陣列,我想起來拆分此陣列分成的3

段在普通的舊的JavaScript,我會使用以下內容。

var chunk_size = 3; 
var arr = PARTIES; 
var groups = arr.map(function(e,i){ 
    return i%chunk_size===0 ? arr.slice(i,i+chunk_size) : null; 
}) 
.filter(function(e){ return e; }); 
PARTIES = groups 

但是,我正在使用TypeScript。是否有任何可能的方式來執行我想用TypeScript實現的目標?

+1

什麼讓你認爲你不能用TypeScript做什麼你可以用JavaScript? – Marty

+0

如果它很簡單,你能告訴我一個如何實現這個功能的例子嗎? @Marty –

+0

對不起,我的意思是,如果事實上在JavaScript中工作,它將在TypeScript中完美地工作:-) – Marty

回答

4

你的JavaScript代碼:

var chunk_size = 3; 
var arr = PARTIES; 
var groups = arr.map(function(e,i){ 
    return i%chunk_size===0 ? arr.slice(i,i+chunk_size) : null; 
}) 
.filter(function(e){ return e; }); 
PARTIES = groups 

是不正確的。如果是這將是有效的打字稿和它只是工作,因爲JavaScript是打字稿https://basarat.gitbooks.io/typescript/content/docs/why-typescript.html :)

修復

以下是工作示例:

const PARTIES = [ 
    { id: 1, title: "Main Event", description: "The biggest, most extravagant event in the last 10,000,000 years." }, 
    { id: 2, title: "Secondary Event", description: "The not as biggest, less extravagant event in the last 10,000,000 years." }, 
    { id: 3, title: "Another Event", description: "N/A" }, 
    { id: 4, title: "Another Event", description: "N/A" }, 
    { id: 5, title: "Another Event", description: "N/A" }, 
    { id: 6, title: "Another Event", description: "N/A" }, 
    { id: 7, title: "Another Event", description: "N/A" }, 
    { id: 8, title: "Another Event", description: "N/A" }, 
    { id: 9, title: "Another Event", description: "N/A" }, 
    { id: 10, title: "Another Event", description: "N/A" } 
]; 

var chunk_size = 3; 
const groups = PARTIES.map(function(e,i){ 
    return i%chunk_size===0 ? PARTIES.slice(i,i+chunk_size) : null; 
}) 
.filter(x=>!!x) 

console.log(groups); 

的一些注意事項的修復:

+0

我在一個類中做了它,會影響它嗎? –

+0

@JeromeCarter我已經發布了固定代碼 – basarat

+0

謝謝,夥計。我試圖從課堂上做到這一點。 @basarat –