我正在使用Angular2创建一个应用程序,我有一系列派对。
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实现的目标?
答案 0 :(得分: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
不正确。如果它是它将是有效的TypeScript 并且它将起作用,因为JavaScript是TypeScript 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);
有关修复的一些注意事项:
[]
)与groups
([][]
)的类型不同,因此您不想再分配boolean
中使用真filter
而不是真值/错误检查。更多:https://basarat.gitbooks.io/typescript/content/docs/tips/truthy.html