简体   繁体   中英

Web3 Library Javascript - getAccounts vs accounts.wallet[0]

I have the following code:

const web3 = new Web3(window.ethereum);

console.log('Accounts:', await web3.eth.getAccounts()); 

console.log('Wallet Account:', web3.eth.accounts.wallet[0]);

This returns me 2 different things. The first one, returns me "Accounts: 0xEF..42a3", which is my wallet address, while the other one returns me "undefined"

Why are these two ways so different if they apply to the same area?

The documentation for web3.eth.getAccounts() reads as follows:

Returns a list of accounts the node controls.

Returns:

Promise returns Array - An array of addresses controlled by node.

While the documentation for web3.eth.accounts reads as follows:

The web3.eth.accounts [object] contains functions to generate Ethereum accounts and sign transactions and data.

So, they do not refer to the same thing, and web.eth.getAccounts() is what you are looking for . web3.eth.getAccounts() returns an array of accounts, but web.eth.accounts is an object full of functions do general operations.

You might have been confused that web.eth.accounts.wallet[0] returns undefined instead of an error. This is just a weird JS thing. In JS, arrays are actually objects with numerical keys. So, wallet[0] actually means "get the value for the key 0 from the object wallet ". Because wallet is an object, no error is returned. However, wallet has no key 0 , so undefined is returned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM