在 JavaScript 关联数组中动态创建键

发布于 2024-07-10 03:57:30 字数 428 浏览 7 评论 0原文

到目前为止我找到的所有文档都是更新已经创建的密钥:

 arr['key'] = val;

我有一个像这样的字符串: " name = oscar "

我想最终得到这样的结果

{ name: 'whatever' }

: ,分割字符串并获取第一个元素,然后将其放入字典中。

代码

var text = ' name = oscar '
var dict = new Array();
var keyValuePair = text.split(' = ');
dict[ keyValuePair[0] ] = 'whatever';
alert( dict ); // Prints nothing.

All the documentation I've found so far is to update keys that are already created:

 arr['key'] = val;

I have a string like this: " name = oscar "

And I want to end up with something like this:

{ name: 'whatever' }

That is, split the string and get the first element, and then put that in a dictionary.

Code

var text = ' name = oscar '
var dict = new Array();
var keyValuePair = text.split(' = ');
dict[ keyValuePair[0] ] = 'whatever';
alert( dict ); // Prints nothing.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

那些过往 2024-07-17 03:57:30

不知何故,所有示例虽然运行良好,但都过于复杂:

  • 它们使用 new Array() ,这对于简单的关联数组(又名字典)来说是一种过度杀戮(也是一种开销)。
  • 更好的使用new Object()。 它工作得很好,但是为什么要额外输入这些内容呢?

这个问题被标记为“初学者”,所以让我们简单点。

在 JavaScript 中使用字典的超级简单方法或“为什么 JavaScript 没有特殊的字典对象?”:

// Create an empty associative array (in JavaScript it is called ... Object)
var dict = {};   // Huh? {} is a shortcut for "new Object()"

// Add a key named fred with value 42
dict.fred = 42;  // We can do that because "fred" is a constant
                 // and conforms to id rules

// Add a key named 2bob2 with value "twins!"
dict["2bob2"] = "twins!";  // We use the subscript notation because
                           // the key is arbitrary (not id)

// Add an arbitrary dynamic key with a dynamic value
var key = ..., // Insanely complex calculations for the key
    val = ...; // Insanely complex calculations for the value
dict[key] = val;

// Read value of "fred"
val = dict.fred;

// Read value of 2bob2
val = dict["2bob2"];

// Read value of our cool secret key
val = dict[key];

现在让我们更改值:

// Change the value of fred
dict.fred = "astra";
// The assignment creates and/or replaces key-value pairs

// Change the value of 2bob2
dict["2bob2"] = [1, 2, 3];  // Any legal value can be used

// Change value of our secret key
dict[key] = undefined;
// Contrary to popular beliefs, assigning "undefined" does not remove the key

// Go over all keys and values in our dictionary
for (key in dict) {
  // A for-in loop goes over all properties, including inherited properties
  // Let's use only our own properties
  if (dict.hasOwnProperty(key)) {
    console.log("key = " + key + ", value = " + dict[key]);
  }
}

删除值也很容易:

// Let's delete fred
delete dict.fred;
// fred is removed, but the rest is still intact

// Let's delete 2bob2
delete dict["2bob2"];

// Let's delete our secret key
delete dict[key];

// Now dict is empty

// Let's replace it, recreating all original data
dict = {
  fred:    42,
  "2bob2": "twins!"
  // We can't add the original secret key because it was dynamic, but
  // we can only add static keys
  // ...
  // oh well
  temp1:   val
};
// Let's rename temp1 into our secret key:
if (key != "temp1") {
  dict[key] = dict.temp1; // Copy the value
  delete dict.temp1;      // Kill the old key
} else {
  // Do nothing; we are good ;-)
}

Somehow all examples, while work well, are overcomplicated:

  • They use new Array(), which is an overkill (and an overhead) for a simple associative array (AKA dictionary).
  • The better ones use new Object(). It works fine, but why all this extra typing?

This question is tagged "beginner", so let's make it simple.

The über-simple way to use a dictionary in JavaScript or "Why doesn't JavaScript have a special dictionary object?":

// Create an empty associative array (in JavaScript it is called ... Object)
var dict = {};   // Huh? {} is a shortcut for "new Object()"

// Add a key named fred with value 42
dict.fred = 42;  // We can do that because "fred" is a constant
                 // and conforms to id rules

// Add a key named 2bob2 with value "twins!"
dict["2bob2"] = "twins!";  // We use the subscript notation because
                           // the key is arbitrary (not id)

// Add an arbitrary dynamic key with a dynamic value
var key = ..., // Insanely complex calculations for the key
    val = ...; // Insanely complex calculations for the value
dict[key] = val;

// Read value of "fred"
val = dict.fred;

// Read value of 2bob2
val = dict["2bob2"];

// Read value of our cool secret key
val = dict[key];

Now let's change values:

// Change the value of fred
dict.fred = "astra";
// The assignment creates and/or replaces key-value pairs

// Change the value of 2bob2
dict["2bob2"] = [1, 2, 3];  // Any legal value can be used

// Change value of our secret key
dict[key] = undefined;
// Contrary to popular beliefs, assigning "undefined" does not remove the key

// Go over all keys and values in our dictionary
for (key in dict) {
  // A for-in loop goes over all properties, including inherited properties
  // Let's use only our own properties
  if (dict.hasOwnProperty(key)) {
    console.log("key = " + key + ", value = " + dict[key]);
  }
}

Deleting values is easy too:

// Let's delete fred
delete dict.fred;
// fred is removed, but the rest is still intact

// Let's delete 2bob2
delete dict["2bob2"];

// Let's delete our secret key
delete dict[key];

// Now dict is empty

// Let's replace it, recreating all original data
dict = {
  fred:    42,
  "2bob2": "twins!"
  // We can't add the original secret key because it was dynamic, but
  // we can only add static keys
  // ...
  // oh well
  temp1:   val
};
// Let's rename temp1 into our secret key:
if (key != "temp1") {
  dict[key] = dict.temp1; // Copy the value
  delete dict.temp1;      // Kill the old key
} else {
  // Do nothing; we are good ;-)
}
梦纸 2024-07-17 03:57:30

使用第一个例子。 如果该密钥不存在,则会添加该密钥。

var a = new Array();
a['name'] = 'oscar';
alert(a['name']);

会弹出一个包含“oscar”的消息框。

尝试:

var text = 'name = oscar'
var dict = new Array()
var keyValuePair = text.replace(/ /g,'').split('=');
dict[ keyValuePair[0] ] = keyValuePair[1];
alert( dict[keyValuePair[0]] );

Use the first example. If the key doesn't exist it will be added.

var a = new Array();
a['name'] = 'oscar';
alert(a['name']);

Will pop up a message box containing 'oscar'.

Try:

var text = 'name = oscar'
var dict = new Array()
var keyValuePair = text.replace(/ /g,'').split('=');
dict[ keyValuePair[0] ] = keyValuePair[1];
alert( dict[keyValuePair[0]] );
甚是思念 2024-07-17 03:57:30

JavaScript 没有关联数组。 它有对象

以下代码行都执行完全相同的操作 - 将对象上的“名称”字段设置为“orion”。

var f = new Object(); f.name = 'orion';
var f = new Object(); f['name'] = 'orion';
var f = new Array(); f.name = 'orion';
var f = new Array(); f['name'] = 'orion';
var f = new XMLHttpRequest(); f['name'] = 'orion';

看起来您有一个关联数组,因为 Array 也是一个 Object - 但是您实际上根本没有将内容添加到数组中; 您正在对象上设置字段。

现在已经清楚了,这是您的示例的可行解决方案:

var text = '{ name = oscar }'
var dict = new Object();

// Remove {} and spaces
var cleaned = text.replace(/[{} ]/g, '');

// Split into key and value
var kvp = cleaned.split('=');

// Put in the object
dict[ kvp[0] ] = kvp[1];
alert( dict.name ); // Prints oscar.

JavaScript does not have associative arrays. It has objects.

The following lines of code all do exactly the same thing - set the 'name' field on an object to 'orion'.

var f = new Object(); f.name = 'orion';
var f = new Object(); f['name'] = 'orion';
var f = new Array(); f.name = 'orion';
var f = new Array(); f['name'] = 'orion';
var f = new XMLHttpRequest(); f['name'] = 'orion';

It looks like you have an associative array because an Array is also an Object - however you're not actually adding things into the array at all; you're setting fields on the object.

Now that that is cleared up, here is a working solution to your example:

var text = '{ name = oscar }'
var dict = new Object();

// Remove {} and spaces
var cleaned = text.replace(/[{} ]/g, '');

// Split into key and value
var kvp = cleaned.split('=');

// Put in the object
dict[ kvp[0] ] = kvp[1];
alert( dict.name ); // Prints oscar.
走过海棠暮 2024-07-17 03:57:30

作为对 MK_Dev 的响应,我们可以迭代,但不能连续(为此,显然需要一个数组)。

快速 Google 搜索会显示JavaScript 中的哈希表

用于循环哈希中的值的示例代码(来自上述链接):

var myArray = new Array();
myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;

// Show the values stored
for (var i in myArray) {
    alert('key is: ' + i + ', value is: ' + myArray[i]);
}

In response to MK_Dev, one is able to iterate, but not consecutively (for that, obviously an array is needed).

A quick Google search brings up hash tables in JavaScript.

Example code for looping over values in a hash (from the aforementioned link):

var myArray = new Array();
myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;

// Show the values stored
for (var i in myArray) {
    alert('key is: ' + i + ', value is: ' + myArray[i]);
}
残疾 2024-07-17 03:57:30

原始代码(我添加了行号,以便可以参考它们):

1  var text = ' name = oscar '
2  var dict = new Array();
3  var keyValuePair = text.split(' = ');
4  dict[ keyValuePair[0] ] = 'whatever';
5  alert( dict ); // Prints nothing.

几乎就在那里...

  • 第 1 行:您应该对文本进行 trim ,使其成为 name = oscar.

  • 第 3 行:只要你的平等者周围总是就可以。
    最好不要在第 1 行中 trim。使用 = 并修剪每个 keyValuePair

  • 在 3 之后和 4 之前添加一行:

     key = keyValuePair[0];` 
      
  • 第 4 行:现在变为:

     dict[key] = keyValuePair[1]; 
      
  • 第 5 行:更改为:

    alert( dict['name'] );   // 它将打印出“oscar” 
      

我试图说 dict[keyValuePair[0]] 不起作用。 您需要将一个字符串设置为 keyValuePair[0] 并将其用作关联键。 这是我让自己工作的唯一方法。 设置完成后,您可以使用数字索引或键入引号来引用它。

The original code (I added the line numbers so can refer to them):

1  var text = ' name = oscar '
2  var dict = new Array();
3  var keyValuePair = text.split(' = ');
4  dict[ keyValuePair[0] ] = 'whatever';
5  alert( dict ); // Prints nothing.

Almost there...

  • line 1: you should do a trim on text so it is name = oscar.

  • line 3: okay as long as you always have spaces around your equal.
    It might be better to not trim in line 1. Use = and trim each keyValuePair

  • add a line after 3 and before 4:

      key = keyValuePair[0];`
    
  • line 4: Now becomes:

      dict[key] = keyValuePair[1];
    
  • line 5: Change to:

      alert( dict['name'] );  // It will print out 'oscar'
    

I'm trying to say that the dict[keyValuePair[0]] does not work. You need to set a string to keyValuePair[0] and use that as the associative key. That is the only way I got mine to work. After you have set it up, you can either refer to it with numeric index or key in quotes.

酒几许 2024-07-17 03:57:30

所有现代浏览器都支持 Map,是一个键/值数据结构。 使用 Map 比使用 Object 更好的原因有几个:

  • 对象有原型,因此映射中有默认键。
  • 对象的键是字符串,它们可以是映射的任何值。
  • 您可以轻松获取地图的大小,但必须跟踪对象的大小。

示例:

var myMap = new Map();

var keyObj = {},
    keyFunc = function () {},
    keyString = "a string";

myMap.set(keyString, "value associated with 'a string'");
myMap.set(keyObj, "value associated with keyObj");
myMap.set(keyFunc, "value associated with keyFunc");

myMap.size; // 3

myMap.get(keyString);    // "value associated with 'a string'"
myMap.get(keyObj);       // "value associated with keyObj"
myMap.get(keyFunc);      // "value associated with keyFunc"

如果您希望垃圾收集未从其他对象引用的键,请考虑使用 WeakMap 而不是 Map。

All modern browsers support a Map, which is a key/value data structure. There are a couple of reasons that make using a Map better than Object:

  • An Object has a prototype, so there are default keys in the map.
  • The keys of an Object are strings, where they can be any value for a Map.
  • You can get the size of a Map easily while you have to keep track of size for an Object.

Example:

var myMap = new Map();

var keyObj = {},
    keyFunc = function () {},
    keyString = "a string";

myMap.set(keyString, "value associated with 'a string'");
myMap.set(keyObj, "value associated with keyObj");
myMap.set(keyFunc, "value associated with keyFunc");

myMap.size; // 3

myMap.get(keyString);    // "value associated with 'a string'"
myMap.get(keyObj);       // "value associated with keyObj"
myMap.get(keyFunc);      // "value associated with keyFunc"

If you want keys that are not referenced from other objects to be garbage collected, consider using a WeakMap instead of a Map.

冷月断魂刀 2024-07-17 03:57:30

我认为如果您像这样创建它会更好:

var arr = [];

arr = {
   key1: 'value1',
   key2:'value2'
};

有关更多信息,请看一下:

JavaScript 数据结构 - 关联数组

I think it is better if you just created it like this:

var arr = [];

arr = {
   key1: 'value1',
   key2:'value2'
};

For more info, take a look at this:

JavaScript Data Structures - Associative Array

最佳男配角 2024-07-17 03:57:30
var obj = {};

for (i = 0; i < data.length; i++) {
    if(i%2==0) {
        var left = data[i].substring(data[i].indexOf('.') + 1);
        var right = data[i + 1].substring(data[i + 1].indexOf('.') + 1);

        obj[left] = right;
        count++;
    }
}

console.log("obj");
console.log(obj);

// Show the values stored
for (var i in obj) {
    console.log('key is: ' + i + ', value is: ' + obj[i]);
}


}
};
}
var obj = {};

for (i = 0; i < data.length; i++) {
    if(i%2==0) {
        var left = data[i].substring(data[i].indexOf('.') + 1);
        var right = data[i + 1].substring(data[i + 1].indexOf('.') + 1);

        obj[left] = right;
        count++;
    }
}

console.log("obj");
console.log(obj);

// Show the values stored
for (var i in obj) {
    console.log('key is: ' + i + ', value is: ' + obj[i]);
}


}
};
}
囍笑 2024-07-17 03:57:30
var myArray = new Array();
myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;

// Show the values stored
for (var i in myArray) {
    alert('key is: ' + i + ', value is: ' + myArray[i]);
}

这没问题,但它会迭代数组对象的每个属性。

如果您只想迭代 myArray.one、myArray.two... 属性,您可以这样尝试:

myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;
myArray.push("one");
myArray.push("two");
myArray.push("three");
for(var i=0;i<maArray.length;i++){
    console.log(myArray[myArray[i]])
}

现在您可以通过 myArray["one"] 访问这两个属性,并且仅迭代这些属性。

var myArray = new Array();
myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;

// Show the values stored
for (var i in myArray) {
    alert('key is: ' + i + ', value is: ' + myArray[i]);
}

This is ok, but it iterates through every property of the array object.

If you want to only iterate through the properties myArray.one, myArray.two... you try like this:

myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;
myArray.push("one");
myArray.push("two");
myArray.push("three");
for(var i=0;i<maArray.length;i++){
    console.log(myArray[myArray[i]])
}

Now you can access both by myArray["one"] and iterate only through these properties.

陪我终i 2024-07-17 03:57:30
const arrayValues = [
                    "yPnPQpdVgzvSFdxRoyiwMxcx",
                    "yPnPQpdVgzvSFdxRoyiwMxcx",
                    "a96b3Z-rqt6U3QV_1032fxcsa",
                    "iNeoJfVnF7dXqARwnDOhj233dsd"
                ];
                
                const newArr = arrayValues.map((x)=>{
                    return {
                        "_id":x
                    }
                });
     console.log(newArr)

const arrayValues = [
                    "yPnPQpdVgzvSFdxRoyiwMxcx",
                    "yPnPQpdVgzvSFdxRoyiwMxcx",
                    "a96b3Z-rqt6U3QV_1032fxcsa",
                    "iNeoJfVnF7dXqARwnDOhj233dsd"
                ];
                
                const newArr = arrayValues.map((x)=>{
                    return {
                        "_id":x
                    }
                });
     console.log(newArr)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文