代码之家  ›  专栏  ›  技术社区  ›  SamuraiJack

Javascript函数未被调用?范围问题?

  •  -1
  • SamuraiJack  · 技术社区  · 5 年前

    我正在尝试对json对象执行验证。但似乎这种方法 ispoQuantityInvalid 方法根本没有被调用。

    Fiddle

    selectedRows = [{
        "itemNumber": "",
        "lineNumber": 1,
        "description": "PUMP,COMPLETE, P/N E12LYTFS-137",
        "uom": "",
        "poQuantity": "1",
        "recievedQuantity": "3",
        "isMatched": false,
        "p2PLineItemId": "168512",
        "quantityUnitPrice": "1",
        "buyerItemNumber": null
    }];    
    
    
     ispoQuantityInvalid = () => (element, index, array) => {
     alert() //not getting called. 
        return this.isEmpty(element.poQuantity);
      }
    console.log(this.selectedRows)
    
    if (this.selectedRows.some(this.ispoQuantityInvalid)) {
         console.log('po qty is null or empty') //always gets called.
          return;
        }    
    
      isEmpty = (value) => {     
        return (value == null || value.length === 0 || value === '' || value == 0);
      }
    
    1. 尽管 poQuantity 如果不是null、空或0,则验证失败。
    2. 看起来 ispoQuantity无效 方法根本没有被调用。我没有看到警报。

    我在这里错过了什么? 这似乎是一个范围问题。但我使用的箭头函数应该不会导致这个问题,对吧?

    1 回复  |  直到 5 年前
        1
  •  1
  •   marks    5 年前

    改变

     ispoQuantityInvalid = () => (element, index, array) => {
     alert() //not getting called. 
        return this.isEmpty(element.poQuantity);
      }
    

     ispoQuantityInvalid = (element, index, arra) => {
     alert() //not getting called. 
        return this.isEmpty(element.poQuantity);
      }
    

    第一个是返回要调用的函数的函数。因此,内部函数仅可用,但从未被调用。if语句看起来像 if( function(e,i,a) {} ) 这不是false,因此if语句体被执行。