简体   繁体   English

在地图中调用函数时未定义错误 - 打字稿

[英]Function not defined error while calling it inside map - typescript

I have the following map within a function我在函数中有以下地图

mainFunc(){
// other logics

    data.map(function (item) {
      item.number = Math.round(item.number);
      item.total = item.last - item.first;
      item.quantity= item?.quantity ? quantityRange(item?.quantity): '';
    }); 

// other logics
}


quantityRange(quantity){
if(quantity){
   if(quantity < 100) return "Less Quantity";
   if(quantity < 500) return "Average Quantity";
   else return "Good Quantity"
   }
}

I have the quantityRange() outside the mainFunc() and i am calling it inside the ternary operator inside the map.我在mainFunc() quantityRange()之外有 quantityRange(),我在地图内的三元运算符内调用它。 when i run my code i get the error quantityRange() not defined.当我运行我的代码时,我得到错误quantityRange()未定义。 can we not use function like this inside the map in typescript?我们不能在打字稿的地图中使用这样的功能吗?

Any help would be appreciated.任何帮助,将不胜感激。

mainFunc(){
// other logics
    const self = this; // make sure you are not loosing this
    data.map(function (item) {
      item.number = Math.round(item.number);
      item.total = item.last - item.first;
      item.quantity= item?.quantity ? self.quantityRange(item?.quantity): '';
    }); 

// other logics
}

you should call the method with this keyword, to do so you should bind this.您应该使用 this 关键字调用该方法,为此您应该绑定 this。 There are different ways to do so, one of them is just to save it in variable.有不同的方法可以做到这一点,其中之一就是将其保存在变量中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM