我使用下面的逻辑来获取给定键的i18n字符串。

export function i18n(key) {
  if (entries.hasOwnProperty(key)) {
    return entries[key];
  } else if (typeof (Canadarm) !== 'undefined') {
    try {
      throw Error();
    } catch (e) {
      Canadarm.error(entries['dataBuildI18nString'] + key, e);
    }
  }
  return entries[key];
}

我在我的项目中使用ESLint。我得到以下错误:

不要访问Object。原型方法'hasOwnProperty'从目标对象。 这是一个“no-prototype-builtins”错误。

如何更改代码来解决此错误?我不想禁用这个规则。


当前回答

对于您的具体情况,以下示例将起作用:

if(Object.prototype.hasOwnProperty.call(entries, "key")) {
    //rest of the code
}

OR

if(Object.prototype.isPrototypeOf.call(entries, key)) {
    //rest of the code
}

OR

if({}.propertyIsEnumerable.call(entries, "key")) {
    //rest of the code
}

其他回答

@前面的答案是正确的

用这个:

Object.prototype.hasOwnProperty.call(object, "objectProperty");

你可以使用Object。hasOwn(entries, key)。hasOwn是Object.hasOwnProperty的替代品。

这对我很有用,所以试试吧

let  bug={
 name:"test"
   }
if (bug && typeof bug === 'object' && Object.prototype.hasOwnProperty.call(bug, name)) {

}

对于您的具体情况,以下示例将起作用:

if(Object.prototype.hasOwnProperty.call(entries, "key")) {
    //rest of the code
}

OR

if(Object.prototype.isPrototypeOf.call(entries, key)) {
    //rest of the code
}

OR

if({}.propertyIsEnumerable.call(entries, "key")) {
    //rest of the code
}

这似乎也行得通:

输入关键字

因为这将返回一个布尔是否存在的关键对象?