【问题标题】:item has value but in Uint8Array return 'undefined'item 有值,但在 Uint8Array 中返回 'undefined'
【发布时间】:2018-01-02 18:04:43
【问题描述】:

你好,我有Uint8Array这样的

var ar = new Uint8Array();
ar[0] = 'G';
ar[1] = 0x123;

第二个索引是一个十六进制数,我想检查ar[1] 是否大于零,所以我写了这段代码:

if(ar[1] > 0){
  console.log("OK");
}
else{
  console.log("NOP")
}

但如果我写 console.log(ar[1]) 我会得到“未定义”。这是我创建的一个简单的jsbin

【问题讨论】:

    标签: javascript arrays binary hex


    【解决方案1】:

    AFAIK 条目数需要作为参数传递给构造函数。

    const ar = new Uint8Array(2);
    ar[0] = 'G';
    ar[1] = 0x123;
    
    console.log(ar[1]);
    
    if(ar[1] > 0){
      console.log("OK");
    }
    else{
      console.log("NOP")
    }
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    编辑:再次阅读docs,您可以使用空构造函数new Uint8Array(); // new in ES2017。但是没有任何可行的例子。

    【讨论】:

      【解决方案2】:

      您可以使用UintArray.from() 或将元素的数量传递给构造函数,然后使用括号表示法设置索引的值

      var ar = Uint8Array.from(["G", 0x123]);
      
      if (ar[1] > 0) {
        console.log("OK");
      } else {
        console.log("NOP")
      }

      【讨论】:

        猜你喜欢
        • 2016-06-03
        • 1970-01-01
        • 1970-01-01
        • 2022-12-07
        • 1970-01-01
        • 1970-01-01
        • 2017-03-24
        • 2020-02-25
        • 2018-03-15
        相关资源
        最近更新 更多