javascript - 获取类型错误 : Cannot set property 'data' of undefined

标签 javascript node.js blockchain

当我压缩代码时,我很难找到代码中定义数据的错误。我为我的代码编写了 4 个测试,其中 3 个已经通过。我在测试 3 中遇到错误。

添加这个可以解决问题,但我试图保持简洁。

blockchain.addBlock({data: 'Bears'});

blockchain.addBlock({data: 'Beets'});

blockchain.addBlock({data: 'Battlestar Galatica'});

这是我目前收到错误时所得到的信息。

describe('and the chain contains a block with an invalid field',()=>{
    it('returns false', () => {

        blockchain.chain[2].data = 'some-bad-and-evil-data';

        expect(Blockchain.isValidChain(blockchain.chain)).toBe(false);
        });
    });
FAIL ./blockchain.test.js
  ● Blockchain › isValidChain() › and the chain contains a block with an invalid field › returns false

    TypeError: Cannot set property 'data' of undefined

      54 |     it('returns false', () => {
      55 |
    > 56 |         blockchain.chain[2].data = 'some-bad-and-evil-data';
         |         ^
      57 |
      58 |         expect(Blockchain.isValidChain(blockchain.chain)).toBe(false);
      59 |         });

      at Object.it (blockchain.test.js:56:9)

最佳答案

blockchain.chain 的索引 2 处似乎没有元素。一般来说,这是在尝试访问数组中元素的字段时出现此错误的最可能原因。

换句话说;

someCollection[index].someField

如果您看到包含 UndefinedNullReferenceNullPointer 关键字的错误,则说明您的集合没有 index + 1 个元素。

关于javascript - 获取类型错误 : Cannot set property 'data' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57547998/

相关文章:

javascript - Redux updateElementSaga 已被取消。为什么?

javascript - CSS 转换在 Safari 中立即发生

javascript - AngularJs 将查询字符串发布到 C# Controller

node.js - 尝试加载 Node.js 中的所有 firestore 文档

node.js - 安全存储开源项目中连接数据库的密码

ubuntu - 如何从错误 : flag needs an argument: 'c' in -c? 中纠正

javascript - 未捕获( promise 中)错误 : No "from" address specified in neither the given options, 和默认选项

javascript - jQuery:确认 .html() 是否可添加

blockchain - Composer playground 无法加载示例业务网络

node.js - 为什么将 Ubuntu 升级到 20.04 会从系统中删除 nodejs、mySQL 工作台?