【问题标题】:"object is not extensible" error trying to add field in map function尝试在地图函数中添加字段时出现“对象不可扩展”错误
【发布时间】:2020-05-26 15:12:19
【问题描述】:

我正在尝试使用地图向数组中的项目添加一个新字段:

const newArray = oldArray.map(item => {
    return (item.newField = 'Something');
});

我试过了:

const newArray = oldArray.map(item => {
    item.newField = 'Something';
    return item;
});

但是我得到一个错误:

TypeError: Cannot add property newField, object is not extensible

【问题讨论】:

  • 您是要比较item.newField 还是分配它?这里使用的语法是为了做比较,所以需要===
  • 我正在尝试分配一个新字段。物品将始终被退回。
  • item 可能是原语。
  • 啊!然后你需要在这里使用Object.assignoldArray.map(item => Object.assign({}, item, { newField: 'Something' }));
  • 您需要复制对象才能在此处分配新属性

标签: javascript


【解决方案1】:

您可以像这样使用对象传播(es6 功能):

const newArray = oldArray.map(item => {
    // { ...item } creates a new object and spreads all of "item" items
    // into it. We can then assign a "newField" or overwrite "newField" 
    // if it already exists on "item"
    return { ...item, newField: 'something' };
});

【讨论】:

    【解决方案2】:
    const newArray = oldArray.map(item => {
      return Object.assign({}, item, { newField: 'Something' });
    });
    

    【讨论】:

    • 这里不需要使用const和return,Object.assign({}返回浅克隆,单行lamba(箭头函数)有隐含返回
    【解决方案3】:

    很可能该对象被标记为不可扩展并且您正在运行严格模式。

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cant_define_property_object_not_extensible

    当方法Object.preventExtensions(obj)被调用时,你会得到错误。

    'use strict';
    
    var obj = {};
    Object.preventExtensions(obj);
    
    obj.x = 'foo';
    

    你会得到错误Uncaught TypeError: Cannot add property x, object is not extensible

    【讨论】:

    • 虽然这是真的,但它可能会导致错误,但这里似乎并非如此。
    【解决方案4】:

    或者你也可以通过Object.create(...)克隆对象

    const object1 = {
      foo: 'foo'
    };
    
    // This will prevent extending this object:
    Object.preventExtensions(object1);
    
    const object2 = Object.create(object1);
    
    /**
     * This cloned object has no preventExtensions flag
     * and can thus be extended as you like
     */
    object2.bar = 'bar';
    

    【讨论】:

      猜你喜欢
      • 2020-12-05
      • 2016-06-01
      • 2013-12-13
      • 1970-01-01
      • 2013-09-12
      • 2017-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多