【问题标题】:How Do I Separate an Array in Typescript如何在 Typescript 中分隔数组
【发布时间】:2016-07-27 04:02:05
【问题描述】:

我正在使用 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 实现的目标?

【问题讨论】:

  • 是什么让你觉得你不能用 TypeScript 做你可以用 JavaScript 做的?
  • 如果这么简单,你能给我展示一个如何实现这个功能的例子吗? @Marty
  • 抱歉,我的意思是,如果某些东西实际上在 JavaScript 中工作,那么它在 TypeScript 中也能正常工作:-)
  • 可以理解,但是这段代码破坏了我的应用程序@Marty
  • 您遇到什么错误?正如 Basarat 所说,原始代码无论如何都是无效的,如果它也是纯 JS,它会破坏您的应用程序。

标签: javascript arrays angularjs typescript


【解决方案1】:

您的 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);

关于修复的一些说明:

【讨论】:

  • 我在课堂上做,会影响吗?
  • 谢谢,伙计。我试图在课堂上做到这一点。 @basarat
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-23
  • 1970-01-01
  • 1970-01-01
  • 2019-09-04
  • 2020-03-11
  • 1970-01-01
相关资源
最近更新 更多