简体   繁体   English

在JavaScript中存储key => value数组的最佳方法?

[英]Best way to store a key=>value array in JavaScript?

What's the best way to store a key=>value array in javascript, and how can that be looped through? 在javascript中存储key=>value数组的最佳方法是什么,以及如何循环?

The key of each element should be a tag, such as {id} or just id and the value should be the numerical value of the id. 每个元素的键应该是一个标记,例如{id}或只是id ,值应该是id的数值。

It should either be the element of an existing javascript class, or be a global variable which could easily be referenced through the class. 它应该是现有javascript类的元素,或者是可以通过类轻松引用的全局变量。

jQuery can be used. 可以使用jQuery。

That's just what a JavaScript object is: 这就是JavaScript对象:

var myArray = {id1: 100, id2: 200, "tag with spaces": 300};
myArray.id3 = 400;
myArray["id4"] = 500;

You can loop through it using for..in loop : 你可以使用for..in循环for..in它:

for (var key in myArray) {
  console.log("key " + key + " has value " + myArray[key]);
}

See also: Working with objects (MDN). 另请参阅: 使用对象 (MDN)。

In ECMAScript6 there is also Map (see the browser compatibility table there): 在ECMAScript6中还有Map (参见那里的浏览器兼容性表):

  • An Object has a prototype, so there are default keys in the map. Object有一个原型,因此地图中有默认键。 This could be bypassed by using map = Object.create(null) since ES5, but was seldomly done. 这可以通过使用自ES5以来的map = Object.create(null)来绕过,但很少完成。

  • The keys of an Object are Strings and Symbols, where they can be any value for a Map. Object的键是字符串和符号,它们可以是Map的任何值。

  • You can get the size of a Map easily while you have to manually keep track of size for an Object. 您必须手动跟踪对象的大小,才能轻松获得Map的大小。

If I understood you correctly: 如果我理解正确的话:

var hash = {};
hash['bob'] = 123;
hash['joe'] = 456;

var sum = 0;
for (var name in hash) {
    sum += hash[name];
}
alert(sum); // 579

You can use Map . 你可以使用Map

  • A new data structure introduced in JavaScript ES6. JavaScript ES6中引入的新数据结构。
  • Alternative to JavaScript Object for storing key/value pairs. 用于存储键/值对的JavaScript对象的替代方法。
  • Has useful methods for iteration over the key/value pairs. 具有用于迭代键/值对的有用方法。
var map = new Map();
map.set('name', 'John');
map.set('id', 11);

// Get the full content of the Map
console.log(map); // Map { 'name' => 'John', 'id' => 11 }

Get value of the Map using key 使用键获取Map的值

console.log(map.get('name')); // John 
console.log(map.get('id')); // 11

Get size of the Map 获取地图的大小

console.log(map.size); // 2

Check key exists in Map 地图中存在检查键

console.log(map.has('name')); // true
console.log(map.has('age')); // false

Get keys 获取密钥

console.log(map.keys()); // MapIterator { 'name', 'id' }

Get values 获得价值

console.log(map.values()); // MapIterator { 'John', 11 }

Get elements of the Map 获取地图的元素

for (let element of map) {
  console.log(element);
}

// Output:
// [ 'name', 'John' ]
// [ 'id', 11 ]

Print key value pairs 打印键值对

for (let [key, value] of map) {
  console.log(key + " - " + value);
}

// Output: 
// name - John
// id - 11

Print only keys of the Map 仅打印地图的键

for (let key of map.keys()) {
  console.log(key);
}

// Output:
// name
// id

Print only values of the Map 仅打印地图的值

for (let value of map.values()) {
  console.log(value);
}

// Output:
// John
// 11

In javascript a key value array is stored as an object. 在javascript中,键值数组存储为对象。 There are such things as arrays in javascript, but they are also somewhat considered objects still, check this guys answer - Why can I add named properties to an array as if it were an object? 在javascript中有像数组这样的东西,但它们在某种程度上也被认为是对象,请检查这些人的答案 - 为什么我可以将命名属性添加到数组中,就像它是一个对象一样?

Arrays are typically seen using square bracket syntax, and objects ("key=>value" arrays) using curly bracket syntax, though you can access and set object properties using square bracket syntax as Alexey Romanov has shown. 通常使用方括号语法和使用大括号语法的对象(“key => value”数组)可以看到数组,尽管您可以使用方括号语法访问和设置对象属性,如Alexey Romanov所示。

Arrays in javascript are typically used only with numeric, auto incremented keys, but javascript objects can hold named key value pairs, functions and even other objects as well. javascript中的数组通常仅用于数字,自动递增的键,但javascript对象也可以包含命名键值对,函数甚至其他对象。

Simple Array eg. 简单数组例如。

$(document).ready(function(){

    var countries = ['Canada','Us','France','Italy'];
    console.log('I am from '+countries[0]);
    $.each(countries, function(key, value) {
        console.log(key, value);
    });

});

Output - 输出 -

0 "Canada" 0“加拿大”

1 "Us" 1“我们”

2 "France" 2“法国”

3 "Italy" 3“意大利”

We see above that we can loop a numerical array using the jQuery.each function and access info outside of the loop using square brackets with numerical keys. 我们在上面看到,我们可以使用jQuery.each函数循环数值数组,并使用带数字键的方括号访问循环外部的信息。

Simple Object (json) 简单对象(json)

$(document).ready(function(){

    var person = {
        name: "James",
        occupation: "programmer",
        height: {
            feet: 6,
            inches: 1
        },
    }

    console.log("My name is "+person.name+" and I am a "+person.height.feet+" ft "+person.height.inches+" "+person.occupation);

    $.each(person, function(key, value) {
        console.log(key, value);
    });

});

Output - 输出 -

My name is James and I am a 6 ft 1 programmer 我的名字是詹姆斯,我是一个6英尺1的程序员

name James 詹姆斯

occupation programmer 职业程序员

height Object {feet: 6, inches: 1} height Object {feet:6,inches:1}

In a language like php this would be considered a multidimensional array with key value pairs, or an array within an array. 在像php这样的语言中,这将被认为是具有键值对的多维数组,或者是数组中的数组。 I'm assuming because you asked about how to loop through a key value array you would want to know how to get an object (key=>value array) like the person object above to have, let's say, more than one person. 我假设是因为你问过如何循环键值数组你想知道如何获得一个对象(key => value array),就像上面的person对象一样,让我们​​说,不止一个人。

Well, now that we know javascript arrays are used typically for numeric indexing and objects more flexibly for associative indexing, we will use them together to create an array of objects that we can loop through, like so - 好吧,既然我们知道javascript数组通常用于数字索引,对象更灵活地用于关联索引,我们将一起使用它们来创建一个我们可以遍历的对象数组,就像这样 -

JSON array (array of objects) - JSON数组(对象数组) -

$(document).ready(function(){

    var people = [
        {
            name: "James",
            occupation: "programmer",
            height: {
                feet: 6,
                inches: 1
            }
        }, {
            name: "Peter",
            occupation: "designer",
            height: {
                feet: 4,
                inches: 10
            }
        }, {
            name: "Joshua",
            occupation: "CEO",
            height: {
                feet: 5,
                inches: 11
            }
        }
    ];

    console.log("My name is "+people[2].name+" and I am a "+people[2].height.feet+" ft "+people[2].height.inches+" "+people[2].occupation+"\n");

    $.each(people, function(key, person) {
        console.log("My name is "+person.name+" and I am a "+person.height.feet+" ft "+person.height.inches+" "+person.occupation+"\n");
    });

});

Output - 输出 -

My name is Joshua and I am a 5 ft 11 CEO 我的名字是Joshua,我是一名5英尺11的CEO

My name is James and I am a 6 ft 1 programmer 我的名字是詹姆斯,我是一个6英尺1的程序员

My name is Peter and I am a 4 ft 10 designer 我的名字是彼得,我是一个4英尺10的设计师

My name is Joshua and I am a 5 ft 11 CEO 我的名字是Joshua,我是一名5英尺11的CEO

Note that outside the loop I have to use the square bracket syntax with a numeric key because this is now an numerically indexed array of objects, and of course inside the loop the numeric key is implied. 请注意,在循环外部我必须使用方括号语法和数字键,因为这现在是一个数字索引的对象数组,当然在循环内部隐含数字键。

Simply do this 只需这样做

var key = "keyOne";
var obj = {};
obj[key] = someValue;

I know its late but it might be helpful for those that want other ways. 我知道它已经很晚了但对那些想要其他方式的人来说可能会有所帮助。 Another way array key=>values can be stored is by using an array method called map(); 另一种可以存储数组key =>值的方法是使用一个名为map()的数组方法; ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map ) you can use arrow function too https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map )你也可以使用箭头功能


    var countries = ['Canada','Us','France','Italy'];  
// Arrow Function
countries.map((value, key) => key+ ' : ' + value );
// Anonomous Function
countries.map(function(value, key){
return key + " : " + value;
});

Today we released our new package called laravel-blade-javascript. 今天我们发布了名为laravel-blade-javascript的新软件包。 It provides you with a javascript Blade directive to export PHP variables to JavaScript. 它为您提供了一个javascript Blade指令,用于将PHP变量导出到JavaScript。 So it basically does the same as Jeffrey Way's popular PHP-Vars-To-Js-Transformer package but instead of exporting variables in the controller our package does it a view. 所以它基本上和Jeffrey Way流行的PHP-Vars-To-Js-Transformer包一样,但是不是在控制器中导出变量,而是我们的包给它一个视图。

Here's an example of how it can be used: 以下是如何使用它的示例:

@javascript('key', 'value')

The rendered view will output: 渲染视图将输出:

<script type="text/javascript">window['key'] = 'value';</script>

So in your browser you now have access to a key variable: 因此,在您的浏览器中,您现在可以访问一个关键变量:

console.log(key); //outputs "value"

You can also use a single argument: 您还可以使用单个参数:

@javascript(['key' => 'value'])

Which will output the same as the first example. 其输出与第一个示例相同。

You can also use the config file to set up a namespace where all exported JavaScript variables should reside in. 您还可以使用配置文件来设置所有导出的JavaScript变量应驻留在其中的命名空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM