2017-07-27 24 views
1

您好我有Uint8Array這樣項目具有價值,但在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

回答

2

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。但是沒有任何工作的例子。

1

可以使用UintArray.from()或通過元件的數量來構造,然後用括號表示法

var ar = Uint8Array.from(["G", 0x123]); 
 

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

設置索引的值