无法读取 null 的属性'includes'"



我正在使用 Vue.js 和 JavaScript。

我有一个名为products的对象数组,每个对象都有名为smallest_unit_barcodeproperty。我只想过滤带有条形码的产品,例如value,所以我做了这个功能:

if (value != '') {
var results = this.products.filter(obj=>obj.smallest_unit_barcode.includes(value));
var results = results.slice(Math.max(results.length - 20, 0))
this.pos_quick_lunch = results;
}

一切正常,但如果obj.smallest_unit_barcode == null,我收到此错误:

Error in v-on handler: "TypeError: Cannot read property 'includes' of null"

过滤产品数组时如何忽略null值?

在尝试访问该属性之前与null进行比较:

obj => obj.smallest_unit_barcode !== null && obj.smallest_unit_barcode.includes(value)

由于&&短路,如果左操作数的计算结果为 false,则不会计算右操作数。

简单的答案是,你可以使用

if (value != '') {
var results = this.products.filter(obj=>obj?.smallest_unit_barcode?.includes(value));
var results = results.slice(Math.max(results.length - 20, 0))
this.pos_quick_lunch = results;
}

相关内容

最新更新