如何在JavaScript中创建键/值对列表

How to Create a list of key/value pairs in JavaScript

本文关键字:列表 创建 JavaScript      更新时间:2023-09-26

我有一个数组中的股票列表。每个股票都属于一个扇区,例如

CBB , VZ belongs to Communications Sector 
UPS , RRTS belongs to Transportation Sector 
AAC belongs to Health  Sector 

当我在数组中循环时,输出是

CBB
VZ
UPS
RRTS
AAC 

我要求以这种方式显示

CBB  Communications
VZ   Communications
UPS  Transportation
RRTS Transportation
AAC   Health

我的代码

$(document).ready(function() {
   var list_of_stocks= [
    "CBB",
    "VZ",
    "UPS",
    "RRTS",
    "AAC "
]
for(var i=0;i<list_of_stocks.length;i++)
{
console.log(list_of_stocks[i]);
}
});

http://jsfiddle.net/n3fmw1mw/202/带有上述代码

如何维护另一个键值对列表结构来有效地实现

(我不希望修改数组list_of_stocks),所以想要创建另一个键值对列表。感谢您阅读此

您可以使用javascript对象:

var list_of_stocks= {
  "CBB": "Communications",
  "VZ": "Communications",
  "UPS": "Transportation",
  "RRTS": "Transportation",
  "AAC": "Heath"
};
for (var key in list_of_stocks) {
  if (list_of_stocks.hasOwnProperty(key)) {
    console.log(key + " -> " + list_of_stocks[key]);
  }
}

请参阅http://jsfiddle.net/n3fmw1mw/204/

为什么不使用对象来执行此操作?

obj = {
     communications: ['CBB', 'VZ'],
     transportation: ['UPS', 'RRTS'],
     health: ['AAC']
}

或和多维阵列

newArr = [['CBB', 'VZ'],['UPS', 'RRTS'],['AAC']]

那么您就知道newArr[0]将具有Communications数组等等。