[英]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.