Javascript-在筛选器中测试null
正在寻找有关如何使用筛选器测试null的建议。只要没有一个字段被指定为“null”,它就可以工作。如果任何一条记录为空,则返回以下错误: TypeError:无法读取null的属性“includes” 提前谢谢,非常感谢您的帮助Javascript-在筛选器中测试null,javascript,vue.js,Javascript,Vue.js,正在寻找有关如何使用筛选器测试null的建议。只要没有一个字段被指定为“null”,它就可以工作。如果任何一条记录为空,则返回以下错误: TypeError:无法读取null的属性“includes” 提前谢谢,非常感谢您的帮助 computed: { items () { return this.keyword ? this.records.filter(item =>
computed: {
items () {
return this.keyword
? this.records.filter(item =>
item.name.includes(this.keyword) ||
item.location.includes(this.keyword) ||
item.status.includes(this.keyword) ||
item.vendor.includes(this.keyword) ||
item.model.includes(this.keyword) ||
item.serial.includes(this.keyword) ||
item.product_number.includes(this.keyword)
)
: this.records
},
}
发生错误的原因是至少有一个对象属性设置为null。我将创建一个新函数来处理所有用例和空检查
computed: {
items () {
return this.keyword
? this.records.filter(item =>
this.checkProperty(item.name) ||
this.checkProperty(item.location) ||
this.checkProperty(item.status) ||
this.checkProperty(item.vendor) ||
this.checkProperty(item.model) ||
this.checkProperty(item.serial) ||
this.checkProperty(item.product_number)
)
: this.records
},
}
checkProperty(prop) {
return prop ? prop.includes(this.keyword) : false;
}
您可以定义一个键数组
const keys = ['name', 'location', 'status', 'vendor', 'model', 'serial', 'product_number'];
然后用一个
你可以用一种叫做
是否返回此关键字?this.records.filter(项=>
项目名称?包括(此关键字)||
项目.位置?包括(此.关键字)||
项目状态?包括(此关键字)|
item.vendor?包括(此关键字)||
item.model?包括(此关键字)||
item.serial?包括(此关键字)||
项目.产品编号?包括(此.关键字)
)
:此。记录
您是指项目吗?如果是这样,这可能会有帮助,如果(item==null){return;}这个关键字的值/类型是什么。此解决方案返回以下错误:TypeError:prop.includes不是函数OK,我不明白您为什么会出现此错误,但我很高兴其他人给了您答案
this.keyword
? this.records.filter(item => keys.some(key => item[key]?.includes(this.keyword)))
: this.records