【问题标题】:Reactjs: How to check each of array index containing the value or not?Reactjs:如何检查每个包含值的数组索引?
【发布时间】:2020-11-18 20:41:00
【问题描述】:

这是我的数组:

  const [arr, setArr] = React.useState([
   {
     "id": 1,
     "barcode": "8851907264888",
     "qty" : 1
   }, 
   {
     "id": 2,
     "barcode": "8857124022072",
     "qty": 1
   }
  ]);

这是我的功能:

  const hasBarcode = (arr, barcode) => arr.some(el => el.barcode === barcode);

  const handleUpdate=()=>{
   let x = 8851907264888;
   for(let i = 0;i < arr.length;i++){
     if(hasBarcode(arr[i], x) == true){
        let newArr = [...arr];
        newArr[i].qty = newArr[i].qty + 1;
        setArr(newArr);       
       }
    }
  }

我的问题出在for loop,我想检查每个数组索引,如果每个索引包含与x 相同的barcode,我想为该特定索引添加qty + 1 .但这里显示错误为Cannot read property 'some' of undefined

【问题讨论】:

    标签: javascript arrays reactjs syntax-error typeerror


    【解决方案1】:

    您将对象传递给 hasBarcode() 而不是数组的代码中的错误 你也可以这样做

      const handleUpdate = () => {
        let x = 8851907264888;
        let newArr = arr.map((obj) => {
          if (obj.barcode && obj.barcode == x) {
            obj.qty = obj.qty + 1;
          }
          return obj;
        });
        setArr(newArr);
      };
    

    【讨论】:

      【解决方案2】:

        const hasBarcode = (arr, barcode) => arr.some(el => el.barcode === barcode);
      
        const handleUpdate=()=>{
         let x = 8851907264888;
         for(let i = 0;i < arr.length;i++){
           if(hasBarcode(arr, x) == true){
              let newArr = [...arr];
              newArr[i].qty = newArr[i].qty + 1;
              setArr(newArr);       
             }
          }
        }

      【讨论】:

        【解决方案3】:

        您的代码中的错误在这里

        if(hasBarcode(arr[i], x) == true){
        

        因为您试图将第一个参数是数组的方法应用于对象。

        正确的应该是if(hasBarcode(arr, x) == true){

        不过,您可以使用ArrayfilterforEach 函数执行以下操作:

          const handleUpdate = () => {
            let x = 8851907264888;
            let newArr = [...arr];
            newArr.filter(el => el.barcode === barcode).forEach(el => el.qty++);
            setArr(newArr);  
          }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-05-28
          • 1970-01-01
          • 2022-01-18
          • 2018-08-06
          • 1970-01-01
          • 2019-01-21
          • 1970-01-01
          • 2021-06-06
          相关资源
          最近更新 更多