【问题标题】:array push in javascript associative arrayjavascript关联数组中的数组推送
【发布时间】:2022-01-16 19:05:59
【问题描述】:

我正在尝试创建日期和样式的关联数组。我期待一个像

这样的数组
{   
   dates: [{day: 1, month: 12, year: 2021}, {day: 15, month: 12, year: 2021}],
   styleClass: 'test'
},

我的代码是

var markedDates = [];
markedDates['dates'].push('day: 1, month: 12, year: 2021');
markedDates['dates'].push('day: 15, month: 12, year: 2021');
markedDates['styleClass'].push('test');
console.log(markedDates);

返回错误

【问题讨论】:

  • styleClass 也必须是一个数组:styleClass: ['test']
  • markedDates 应定义为 {}。为什么你不只是复制问题顶部的源代码让我感到困惑。
  • 而您目前正在推送字符串,而不是对象。
  • 熟悉how to access and process nested objects, arrays or JSON以及如何使用create objects,如果需要,可以使用ObjectArray的可用静态和实例方法。
  • 您可能来自 PHP 背景 - 请记住,在 JavaScript 和大多数其他语言中,没有“关联数组”之类的东西。这只是一个对象。

标签: javascript arrays associative-array


【解决方案1】:

问题 1:markedDates 已被定义为一个数组 ([])。要将其定义为对象(这是您的预期输出),请使用 {}。 (在 JavaScript 中没有“关联数组”之类的东西;数组使用 01 等作为索引。对象使用 01keyanother_key 作为索引 [或键,更准确地说]。)

问题 2:您没有在 markedDates 中定义 dates 数组,这将导致引用错误。

问题 3:您将字符串推送到数组而不是对象。这不会出错,但不会产生预期的输出。

问题 4:您尝试将 styleClass 用作数组 - 它只是 markedDates 中的字符串属性。

以逐行方式修复您的代码(保持与原始代码的相似性):

var markedDates = {};

markedDates.dates = [];
markedDates.dates.push({day: 1, month: 12, year: 2021});
markedDates.dates.push({day: 15, month: 12, year: 2021});
markedDates.styleClass = "test";

console.log(markedDates);
.as-console-wrapper { max-height: 100% !important; top: auto; }

但是,如果您在顶部静态定义了预期的输出,则可以直接将其分配给变量:

var markedDates = {
  dates: [{ day: 1, month: 12, year: 2021 }, { day: 15, month: 12, year: 2021 }],
  styleClass: 'test'
};

console.log(markedDates);

【讨论】:

    【解决方案2】:

    你应该考虑的事情 -

    1. 制作一个需要推入更大数组的对象。例如:markedDate 在下面的代码中。
    2. 应直接使用等于运算符分配字符串,无需像在数组中那样推送它
    3. 先将内部字段dates 初始化为数组,然后再推入它

    var markedDates = [];
    var markedDate = {};
    markedDate['dates'] = [];
    markedDate['dates'].push({day: 1, month: 12, year: 2021});
    markedDate['dates'].push({day: 15, month: 12, year: 2021});
    markedDate['styleClass'] = 'test';
    markedDates.push(markedDate);
    console.log(markedDates);

    【讨论】:

    • 不要鼓励使用markedDate['dates'] - 作者将此语法与 PHP 的关联数组混淆了。在 JavaScript 中,它与 markedDate.dates 相同,并且使用带有硬编码值的方括号语法零意义,并且 - 对于甜点 - 更慢。
    • @RoboRobok 也许它是一个动态领域,如果没有另外提及,那就不好假设了:)
    • ['dates'] 是动态字段吗?请承认错误并改正。
    猜你喜欢
    • 2016-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-12
    • 2015-06-01
    • 1970-01-01
    • 2018-11-13
    相关资源
    最近更新 更多