Angular 2 Array.map返回undefined

时间:2018-04-25 13:03:07

标签: javascript angular

我坚持在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);
    }
}

3 个答案:

答案 0 :(得分:2)

我知道这个问题已经回答了,但我有一个解决方案。

  

.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;
}

答案 1 :(得分:1)

您可以使用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

希望能帮到你。

答案 2 :(得分:0)

看起来Typescript打破了回报。通过此修改,我获得了所需的值:

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;
}