[英]Angular 2 Array.map returns undefined
我被困在Angular 2中使用Array.map返回值。
export class TabsPage {
@ViewChild(SuperTabs) superTabs: SuperTabs;
public rootTab: string = 'ProductListPage';
public categories: Array<any>;
public collection_id: number;
public selectedindex: any;
private getArrayIndex(source, target) {
source.map((element, index) => {
if (element.attrs.collection_id === target) {
// Returns the Value i need
console.log('i: ', index);
return index;
}
});
}
constructor(
public navCtrl: NavController,
public navParams: NavParams,
public shopifyClientProvider: ShopifyClientProvider,
private superTabsCtrl: SuperTabsController,
) {
this.categories = navParams.get('collections');
this.collection_id = navParams.get('collection_id');
this.selectedindex = this.getArrayIndex(this.categories, navParams.get('collection_id'));
// Returns undefined
console.log('Index ', this.selectedindex);
}
}
我知道这个问题已经回答,但是我有一个解决方案。
.ts文件代码
private getArrayIndex(source, target) {
let indx = -1;
source.map((element, index) => {
if (element.attrs.collection_id === target) {
// Returns the Value i need
console.log('i: ', index);
indx = index;
}
});
return indx;
}
您可以使用findIndex()以很短的顺序执行此操作:
我不知道您的数据到底是什么样子,但是给定一个数组:
const target = 2;
const source = [
{
attrs: {
collection_id: 1
}
},
{
attrs: {
collection_id: 2
}
},
{
attrs: {
collection_id: 3
}
},
];
const index = source.findIndex(element => element.attrs.collection_id === target);
将为索引返回1
。 如果找不到索引,将返回-1
。
Plunkr: https ://plnkr.co/edit/5B0gnREzyz6IJ3W3
希望对您有所帮助。
看起来打字稿打破了回报。 通过此修改,我得到了所需的值:
private getArrayIndex(source, target) {
let found: number;
source.map((element, index) => {
if (element.attrs.collection_id === target) {
console.log('i: ', index);
found = index;
}
});
return found;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.