簡體   English   中英

比較來自 JSON 和 input.value 的數據

[英]Comparing data from JSON and input.value

我正在研究小型購物車項目。 我在 JSON.file 中有產品,我也有用於查找產品價格的輸入。 我正在使用 class 方法問題是:這是字符串還是數字? -> (3) ['35', '35', '35']


searchItem(data) {
    let that = this

    searchBtn.addEventListener('click', function(e) {
      
       const input = document.querySelector('.input').value

           
       const findItem = data.filter(function(item) {
          if(item.price === input) {
            return item
          }
        })   // this return all data of product so I filtered only prices bellow


        const getItem = findItem.map(item => {
          return item.price
        })                      
 
       // this give:    (3) ['35', '35', '35']  


    
         if(input === getItem) {     
             console.log('same') 
        } else {
          console.log('try it again') 
        }
                         
         // this cond. show me :  console.log('try it again')
         // HOW TO GET:   console.log('same')  
      
       e.preventDefault()
    })


您始終可以運行 typeof 來找出您處理的數據類型

例如

console.log(typeof getItem[0])

也在這里:

        if(input === getItem) {     
             console.log('same') 
        } else {
          console.log('try it again') 
        }

您正在針對整個數組檢查input變量,您必須指定要檢查的數組的哪個項目,例如:

if(input === getItem[0]) {     
             console.log('same') 
        } else {
          console.log('try it again') 
        }

無需代碼分析即可快速直接地回答您的問題,從您的輸入中獲得的任何值都是字符串而不是數字。

因此,如果您從數據中獲得的價格值是 integer,那么您將不得不考慮使用 parseInt() 方法從輸入中解析值。 例子;

const findItem = data.filter(function(item) {
      if(item.price === parseInt(input)) {
        return item
      }
    })

另一件事是 getItem 是一個數組,因此使用輸入中的特定值進行評估必然會失敗。 因此,請使用 getItem[0] 和兩個“==”而不是“===”,正如評論中所建議的那樣。

function searchItem(data) {
        let that = this

        searchBtn.addEventListener('click', function(e) {
        
        const input = document.querySelector('.input').value

            
        const findItem = data.filter(function(item) {
            if(item.price == input) {
                return item
            }
        })   // this return all data of product so I filtered only prices bellow


            const getItem = findItem.map(item => {
                return item.price
            })  
            
            console.log(getItem);
    
        // this give:    (3) ['35', '35', '35']  

            if(input == getItem[0]) {     
                console.log('same') 
            } else {
                console.log('try it again') 
            }
                            
            // this cond. show me :  console.log('try it again')
            // HOW TO GET:   console.log('same')  
        
        e.preventDefault()
        })
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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