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

2023-12-14

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

 arr['key'] = val;

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

我想最终得到这样的结果:

{ name: 'whatever' }

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

Code

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

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

  • 他们使用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 ;-)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 JavaScript 关联数组中动态创建键 的相关文章

随机推荐

  • 为每个发布环境转换 Azure 网站部署的 web.config

    在 Visual Studio Team Services 以前的 Visual Studio Online 中 我有三个发布环境 每个环境都有一个 Azure 网站部署步骤 我可以通过指定获取 Web Uat config 的 Build
  • 使用 solr 索引维基百科转储

    我的机器上安装了 solr 3 6 2 与 tomcat 完美运行 我想使用 solr 索引维基百科转储文件 如何使用 DataImportHandler 执行此操作 还有其他办法吗 我对 xml 没有任何了解 我提到的文件解压后大小约为
  • Hadoop中多个reducer如何只输出一个part-file?

    在我的map reduce 作业中 我使用4 个reducer 来实现reducer 作业 因此 通过这样做 最终输出将生成 4 个部分文件 part 0000part 0001part 0002part 0003 我的问题是 尽管hado
  • 对角带中的遍历矩阵

    我认为这个问题有一个简单的解决方案 几个 for 循环和一些奇特的计数器 但显然它相当复杂 所以我的问题是 你将如何 用 C 语言 编写对角条中方阵的函数遍历 Example 1 2 3 4 5 6 7 8 9 必须按以下顺序遍历 1 2
  • 与 NSPersistentContainer 的核心数据并发

    NOTE 我看过类似的问题 但没有找到描述这种情况的问题 我正在查看 Apple 提供的有关核心数据并发性的以下示例代码 https developer apple com library content documentation Coc
  • Webpack 开发服务器由 nginx 代理的独立子域

    我目前陷入了 webpack dev server 的一个问题 它用错误的端口侦听错误的域 我已经对我的 Symfony 应用程序进行了 docker 化 它有 3 个容器 节点 php 和 nginx 在 Node 容器上 webpack
  • PHP SimpleXML:如何加载 HTML 文件?

    当我尝试使用以下命令将 HTML 文件加载为 XML 时simplexml load string我收到许多关于 HTML 的错误和警告 但它失败了 有没有办法使用 SimpleXML 正确加载 html 文件 该 HTML 文件可能包含不
  • 如何为 Redis 中的数据建模以获得复杂的数据结构?

    我参考了链接 http panuoksala blogspot com 2015 09 redis many to many html开发以下代码 我已经实现了一些代码 看起来到目前为止什么都无法实现 获取用户1组 hget User 1
  • 浮动 div 无法正确堆叠(没有间隙)

    我有一个容器 里面有很多漂浮的物品 问题是 当其中至少一个的大小发生变化时 就会出现间隙 有什么办法可以迫使他们填补这些空白吗 wpr padding 20px wpr span width 260px min height 130px b
  • this.method 不是 setInterval 的函数 [重复]

    这个问题在这里已经有答案了 我有这个简单的代码 var Modules function use strict return TIMER function var timer null return time 100 init functi
  • 如何检测动态库加载

    有没有办法检测应用程序在运行时加载哪些动态库 我看过苹果的文档对于动态库 但似乎没有讨论这一点 要获取应用程序在运行时加载的所有库的列表 import the dynamic linker API import
  • Linux 上的 Python 从管道读取行

    创建管道时os pipe 它返回 2 个文件号 一个读端和一个写端 可以通过以下方式写入和读取os write os read 没有 os readline 可以使用readline吗 import os readEnd writeEnd
  • 我可以关闭 web.xml 中的 HttpSession 吗?

    我想完全消除 HttpSession 我可以在 web xml 中做到这一点吗 我确信有特定于容器的方法可以做到这一点 这就是当我进行 Google 搜索时搜索结果拥挤的原因 附 这是一个坏主意吗 我更喜欢完全禁用某些东西 直到我真正需要它
  • PHP中的日期格式

    我有一个字符串 如下所述 ts 3 11 09 11 18 59 AM 我用的是date 功能 现在我需要将其转换为可读格式 如下所示 11 Mar 2009 我已经尝试了一切使用date 我怎样才能实现这个目标 您需要将其转换为可用于进一
  • iOS 库中可以恢复 iOS 状态吗? -- 找不到名为的故事板

    我有一个带有故事板和控制器类的库 用于实现 iOS 状态保存 要从主应用程序的委托启动库 我使用以下命令 BOOL application UIApplication application didFinishLaunchingWithOp
  • mysqli 忽略表中的第一行

    这是我用来从表中提取数据的代码 require once connect php sql SELECT FROM db news result mysqli gt query sql row mysqli fetch assoc resul
  • Entity Framework 4.1 DbContext 重写 SaveChanges 以审核属性更改

    我正在尝试对一组类中的属性实现属性更改的受限 审核日志 我已成功找到如何设置 CreatedOn ModifiedOn 类型属性 但未能找到如何 查找 已修改的属性 Example public class TestContext DbCo
  • 在android中显示网络错误

    我已经用 webview 创建了应用程序 如果我执行了任何操作并且网络已断开 我想显示一个警报 我尝试过以下方法 在 oncreate 方法中添加了这个 public class AndroidNetTestActivity extends
  • Arm Assembly Raspberry-Pi:将字符串转换为大写

    我正在开发一个程序 其中用户输入他的名字 该程序应将所有小写字母转换为大写 我使用 s 格式来读取字符串 text ldr r0 msj bl printf ldr r0 format ldr r1 string bl scanf data
  • 在 JavaScript 关联数组中动态创建键

    到目前为止我找到的所有文档都是更新已创建的密钥 arr key val 我有一个像这样的字符串 name oscar 我想最终得到这样的结果 name whatever 也就是说 分割字符串并获取第一个元素 然后将其放入字典中 Code v