如何解决名为“length”的数组键问题 jQuery

How to overcome issue with array key called “length” jQuery

我不知道这是否是一个常见问题,但是使用 Magento 2,当属性名称是 length 时,它会给我这个错误:

RangeError: Invalid array length

var self = this;
if (self.attributeNames == null) {
    self.attributeNames = [];
    self.attributeNames['category_names'] = 'Category';
    $.each(this.availableFilters, function(index, item){
        self.attributeNames[item.attribute_code] = item.frontend_label;
    });
}
return self.attributeNames;

这里item.attribute_code是来自Magento属性的动态。因此,当我将属性创建为 length 时,我的代码是:

self.attributeNames[length] = Length;

这让我在使用时出现上述错误。

我该如何克服这个问题?

在第三行你应该分配一个空对象(不是空数组)即self.attributeNames = {}。使用数组,您可以使用 push 方法添加新项目,并仅将值分配给现有项目(按数字索引)。使用对象,您可以像在第四行中那样在运行时添加任何特定字段。