【问题标题】:Function not defined error while calling it inside map - typescript在地图中调用函数时未定义错误 - 打字稿
【发布时间】:2022-11-11 04:08:10
【问题描述】:

我在函数中有以下地图

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

我在mainFunc() 之外有quantityRange(),我在地图内的三元运算符内调用它。当我运行我的代码时,我收到错误 quantityRange() 未定义。我们不能在打字稿的地图中使用这样的功能吗?

任何帮助,将不胜感激。

【问题讨论】:

  • quantityRange 看起来像是方法声明。不是函数。您需要执行 this.quantityRange 但请参阅 How to access the correct this inside a callback - 因为您使用常规函数,所以 this 的值是错误的。您可能需要箭头功能。尽管如果您没有误用 .map() 可能会更好,而是使用更合适的选择 - .forEach() 或者甚至更好,一个常规循环。

标签: javascript typescript


【解决方案1】:
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
}

您应该使用 this 关键字调用该方法,为此您应该绑定 this。有不同的方法可以做到这一点,其中之一就是将其保存在变量中。

【讨论】:

    【解决方案2】:

    是说因为你没有定义它。您没有使用关键字function 来创建您的任何一个函数。您还可以在data.map(function (item) 处放置一个空格;括号不应与此分开。还有其他语法错误。如您所见,我已经修复了其中的大部分。
    它应该是这样的:

    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): ''; // Error is on this line.
        }); 
    
    // other logics
    };
    
    
    function quantityRange(quantity) {
        if (quantity) {
            if (quantity < 100) {
                return "Less Quantity";
            }
            else if (quantity < 500) {
                return "Average Quantity";
            }
            else {
                return "Good Quantity";
            };
        };
    };
    

    我无法弄清楚你对第 6 行做了什么,但这是唯一可能出现错误的地方,你能向我解释一下你对这行的意图是什么,以便我可以帮助纠正它的语法吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-05
      • 2018-04-20
      • 2017-12-22
      • 2018-06-05
      • 1970-01-01
      • 1970-01-01
      • 2019-05-01
      • 2016-10-25
      相关资源
      最近更新 更多