如何在for-of中使用array.slice转换for循环或为生成的列和行映射array.slice?
Posted
技术标签:
【中文标题】如何在for-of中使用array.slice转换for循环或为生成的列和行映射array.slice?【英文标题】:How to convert for loop whit array.slice in for-of or map array.slice for generate col and row? 【发布时间】:2020-04-14 01:52:35 【问题描述】:我在 Angular8 中遇到问题。我需要将数组的for
循环转换为for-of
或array.map
的循环。
我有这段代码,我传递了一个对象数组,我需要将它分成 col 和 row 数组以进行可视化。
private pages = [];
public grid = [];
public col = 2;
public row = 2;
public indexPage = 0;
private gridSize = this.col * this.row;
private items = [
url:'http://url1',
name:'1',
active: false,
,
url:'http://url2',
name:'2',
active: false,
,
url:'http://url3',
name:'3v',
active: false,
,
url:'http://url4',
name:'4v',
active: false,
,
url:'http://url5',
name:'5v',
active: false,
,
url:'http://url6',
name:'6v',
active: false,
,
url:'http://url7',
name:'7v',
active: false,
,
]
ngOnInit()
if(this.col === 0 || this.row === 0)
this.grid = this.items;
else
for (let i = 0; i < this.items.length; i+= this.gridSize)
let page = this.items.slice(i , i+this.gridSize);
this.pages.push(page);
for (let i = 0; i < this.pages.length; i++)
let pageUrl = [];
for(let j = 0; j < this.pages[i].length; j+=this.col)
let urls = this.pages[i].slice(j , j+this.col);
pageUrl.push(urls);
this.grid.push(pageUrl);
我从对象 whit col = 2 的输出;行 = 2; :
pages --> (2) [Array(4), Array(3)] // 2 pages
--> (0) [...,...,...,...] // 1st page - 4 elemet
--> (1) [...,...,...] // 2nd page - 3 element
grid --> (2) [Array(2), Array(2)]
-->(0) [Array(2), Array(2)] // page1 - 2 row
--> (0)[...,]...] // 2 col x row
--> (1)[...,]...] // 2 col x row
--> (1) [Array(2),Array(1)] // page 2 - 2row
--> (0)[...,...] // 2 col x row
--> (1)[...] . // 1col x row
输出是正确的,但是 tslint 在 for 循环中给了我一个错误:
这个简单的预期是“for-of”循环而不是“for”循环 迭代
ps:行和列是可定制的
【问题讨论】:
【参考方案1】:您可以通过以下方式将循环转换为 for-of 循环:
private pages = [];
public grid = [];
public col = 2;
public row = 2;
public indexPage = 0;
private gridSize = this.col * this.row;
private items = [
url:'http://url1',
name:'1',
active: false,
,
url:'http://url2',
name:'2',
active: false,
,
url:'http://url3',
name:'3v',
active: false,
,
url:'http://url4',
name:'4v',
active: false,
,
url:'http://url5',
name:'5v',
active: false,
,
url:'http://url6',
name:'6v',
active: false,
,
url:'http://url7',
name:'7v',
active: false,
,
]
ngOnInit()
if(this.col === 0 || this.row === 0)
this.grid = this.items;
else
for (let item of this.items)
let itemIndex = this.items.indexOf(item);
let page = this.items.slice(itemIndex , itemIndex+this.gridSize);
this.pages.push(page);
for (let iPage of this.pages)
let pageUrl = [];
let j = 0;
for(let jPage of iPage.length)
let urls = iPage.slice(j , j+this.col);
pageUrl.push(urls);
j+=this.col;
this.grid.push(pageUrl);
【讨论】:
以上是关于如何在for-of中使用array.slice转换for循环或为生成的列和行映射array.slice?的主要内容,如果未能解决你的问题,请参考以下文章
Array.prototype.slice.call(arguments)探究