簡體   English   中英

Angular 2 Array.map返回未定義

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM