按照教程进行操作,但无法弄清楚为什么我会收到此消息:"Property 'substring' does not exist on type '() => WordArray'.ts(2



我是一个学习yt区块链可视化代码教程的初学者,但在使用子字符串时收到了以下消息:Property 'substring' does not exist on type '() => WordArray'.ts(2339)

class Block {
constructor(index, timestamp, data, previousHash = ''){
this.index = index;
this.timestamp = timestamp;
this.data = data;
this.previousHash = previousHash;
this.hash = this.calculateHash;
this.nonce = 0;
}
calculateHash(){
return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data) + this.nonce.toString());
}
mineBlock(difficulty){
while(this.hash().substring(0, difficulty) !== Array(difficulty + 1).join("0")){
this.nonce++;
this.hash = this.calculateHash();
}

console.log("Block mined: " + this.hash);
}
}

this.hash是一个返回某种列表的函数。函数本身没有substring方法,只有结果。

您需要使用this.hash()来调用函数以获得其结果。那么this.hash().substring可能起作用。

问题是您试图在非String类上使用substring方法。我假设您使用的是SHA256CryptoJS实现。如果没有,我将删除答案,但您需要将哈希转换为String类才能使用substring方法。SHA256不返回字符串,您需要将其转换为一个字符串,以便对其应用字符串方法。将calculateHash方法更改为这样应该可以使代码工作:

calculateHash(){
return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data) + this.nonce.toString()).toString();
}

更多信息可以在文档中找到

相关内容

最新更新