{ return (item.newField = 'Som-6ren">
gpt4 book ai didi

javascript - "object is not extensible"尝试在 map 函数中添加字段时出错

转载 作者:行者123 更新时间:2023-11-29 11:00:00 25 4
gpt4 key购买 nike

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

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

最佳答案

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

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

关于javascript - "object is not extensible"尝试在 map 函数中添加字段时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49022068/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com