我是一个学习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
方法。我假设您使用的是SHA256
的CryptoJS
实现。如果没有,我将删除答案,但您需要将哈希转换为String
类才能使用substring
方法。SHA256
不返回字符串,您需要将其转换为一个字符串,以便对其应用字符串方法。将calculateHash
方法更改为这样应该可以使代码工作:
calculateHash(){
return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data) + this.nonce.toString()).toString();
}
更多信息可以在文档中找到