【问题标题】:TypeError: Member "length" is read-only and cannot be used to resize arraysTypeError:成员“长度”是只读的,不能用于调整数组大小
【发布时间】:2021-12-15 03:53:54
【问题描述】:

我正在使用这个版本的solidity,pragma solidity >=0.4.22 <0.9.0;

每当我编译松露时,我都会得到这个TypeError: Member "length"。当我将版本更改为0.4.0 时,错误消失了,但我不能使用这个版本。我需要使用这个pragma solidity >=0.4.22 <0.9.0;

这是错误:

     TypeError: Member "length" is read-only and cannot be used to resize arrays.
  --> project:/contracts/Ballot1.sol:23:9:
   |
23 |         proposals.length = _numProposal;
   |         ^^^^^^^^^^^^^^^^

Compilation failed. See above.

【问题讨论】:

  • 为什么不使用slice 来减少数组而不是更改长度属性? proposal = proposal.slice(0, _numProposal);。如果 proposal 被声明为 const 并且因此不可重新分配,则使用另一个变量名。

标签: ethereum solidity truffle


【解决方案1】:

数组的长度属性是只读的,你不能改变它期望改变原始数组大小,相反你可以使用以下任何一种 -

  • Array.prototype.slice()
  • Array.prototype.splice()
  • Array.prototype.filter()

这些方法会改变数组的内容,从而改变它的长度。

splice 将编辑原始数组,而 slice 将从指定的索引范围返回原始数组的副本

const array = [1, 2, 3, 4, 5];
console.log(`original array length - ${array.length}`);
// first parameter is the index of the element to delete, second one is the number of elements to delete from the index
array.splice(0, 1);
console.log(array);
console.log(`new array length - ${array.length}`);

const array = [1, 2, 3, 4, 5];
console.log(`original array length - ${array.length}`);
// first parameter is the start index, second one is the end index
const newArray = array.slice(0, array.length - 1);
console.log(newArray);
console.log(`new array length - ${newArray.length}`);

P.S您还可以使用拼接方法将新元素添加到任何所需的索引

const array = [1, 2, 3, 4, 5];
console.log(`original array length - ${array.length}`);
array.splice(array.length, 0, 6);
console.log(array);
console.log(`new array length - ${array.length}`);

【讨论】:

  • 问题是关于可靠性而不是关于 Javascript
猜你喜欢
  • 1970-01-01
  • 2021-01-27
  • 2019-09-14
  • 2016-10-10
  • 1970-01-01
  • 2011-09-25
  • 2012-05-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多