[英]How to create/maintain a basic associative array/hash with JavaScript?
我正在記錄x軸的加速度數據,因此有兩個值-x值和加速度事件的紀元時間。 我想將它們存儲為散列,其中紀元時間是關鍵,而x值是值。
我創建了一個數組:
var arrX = new Array();
如何添加呢? 像這樣?
arrX[acceleration.timestamp] = acceleration.x
您應該使用一個對象,該對象可以用作此應用程序的一種“關聯數組” 。 一個對象將為您提到的任意非順序鍵提供支持,而數組則不會。
var arrX = {};
arrX[acceleration.timestamp] = acceleration.x;
更多信息:
您可以執行此操作,但無需使用數組。 只需使用這樣的對象
var values = {};
values[acceleration.timestamp] = acceleration.x;
因為如果你做這樣的事情
var x = [];
x[1555] = 500;
您將創建一個包含1556個元素的數組,除1555之外的所有元素都設置為undefined
在Javascript中,如果需要關聯數組,則可以使用對象:
var hash1 = {}; // declare
hash1.first = 'abc'; // set property first to a string
hash1['second'] = 'def'; // set property second to a string
var t = 'third';
hash1[t] = 'ghi'; // set property third to a string
hash1.forth = {a:1, b: 'abc'}; // set property forth to be an object / hash
// with 2 properties
alert (hash1.forth.a); // will alert with 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.