【问题标题】:What does the syntax x:y mean in JavaScript?JavaScript 中的语法 x:y 是什么意思?
【发布时间】:2021-01-07 04:57:08
【问题描述】:

我正在学习有关区块链的课程,其中包含以下代码。 “ index:this.chain.length+1 ”是什么意思?索引是对象 newBlock 中的变量吗?或者它是一个键值对?如果是变量,我们为什么不简单地使用 index=this.chain.length+1 呢?还有对象newBlock的类型是什么?

function Blockchain()
{
  this.chain=[];
  this.newTranscations=[];
}

Blockchain.prototype.createNeBlock = function(nonce,previousBlockHash,hash)
{
  const newBlock ={
    index:this.chain.length+1,
    timestamp:Date.now(),
    // all of the transactions in this block will be the transactions that waiting to be put in a block
    transactions:this.newTranscations,
    // nonce is hust a number giving proof of the transaction
    nonce:nonce,
    hash:hash,
    previousBlockHash: previousBlockHash
  }
  // As we move all the pending transactions to the new block, we clear this array
  this.newTranscations=[];
  this.chain.push(newBlock);
  return newBlock; 
}

【问题讨论】:

  • 在对象字面量中,冒号将属性名称与其将包含的值分开
  • 如果您正在学习的课程中没有说明这一点,我建议您更改课程。

标签: javascript syntax


【解决方案1】:
var Box = {
"playdoh":{"playdoh":["none", "some", "none", "none", "some"]}
};

playdoh 上的 box of playdoh,你正在学习 Objects/Arrays/Maps。

要说出来,那就是

console.log(Box["playdoh"]["playdoh"][0]);
= none

console.log(Box["playdoh"]["playdoh"][4]);
= some

console.log(Box["playdoh"]["playdoh"][5]);
= null (undefined)

相同
console.log(Box.playdoh.playdoh[0]);
= none

console.log(Box.playdoh.playdoh[4]);
= some

console.log(Box.playdoh.playdoh[5]);
= null (undefined)

【讨论】:

  • 那么,这就像python中的字典一样??
  • 是的!确切地说,字典是低级语言中的另一个术语。看起来很眼熟吧? :) 也一样。
【解决方案2】:

这是在 javascript 中初始化名为 newBlock 的对象的几种方法之一。看看这个documentation on MDN

index 属性在本例中为 number 类型,设置为等于 chain[].length + 1

【讨论】:

    猜你喜欢
    • 2013-11-02
    • 2020-06-01
    • 1970-01-01
    • 2013-06-17
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    • 2017-06-11
    • 1970-01-01
    相关资源
    最近更新 更多