【问题标题】:Is there a .push like feature to dynamically add values to an object?是否有类似 .push 的功能可以动态地向对象添加值?
【发布时间】:2015-01-06 06:30:08
【问题描述】:

使用arrays 时,您可以使用.push 方法向数组动态添加新值。使用对象时是否可以这样做?

例如,我有一个文本框,在用户输入内容并单击添加后,您可以将值添加到对象中,以便保存每个值,例如

示例:

{
  message: "This is the first message",
  message: "This is the second message",
  message: "Third message etc"  
}

代码:

$(document).ready(function() {

        // var objArray = [];
        var objObject = {};


        $('#icecream').on('click', function() {
            $(this).animate({'height': '200px'}, 300);  
        });

        $('#add').on('click', function() {
            var value = $('#icecream').val();
            // objArray.push(value);
            // console.log(objArray);
            objObject = {
                message: value,
            }
            console.log(objObject);

        }); 

    });

【问题讨论】:

  • key 在 Object 中必须是唯一的
  • 嗯,那个对象不是你想象的那样......

标签: javascript jquery object


【解决方案1】:
{
  message: "This is the first message",
  message: "This is the second message",
  message: "Third message etc"  
}

这不是一个有效的对象。您不能三次拥有相同的属性(键必须是唯一的)。
您可能需要一个数组:

var messageObj = { 
 messages: [
   "This is the first message",
   "This is the second message",
   "Third message etc"
]};

添加新消息将是:

messageObj.messages.push("Forth message");

您可以为对象动态添加属性:

var obj = {};
var propName = "message";
var propVal = "This is a message";

obj[propName] = propVal;
console.log(obj); // { message: "This is a message" }

JSFIDDLE.

【讨论】:

  • 谢谢,我会在几分钟后接受你的回答 :)
【解决方案2】:

我想你要找的只是objObjects.message='This is the second message';

如果你真的想保留每一个,也许你需要一个数组:

objObjects.messages = [
  'This is the first message',
  'This is the second message',
   // etc
];

【讨论】:

    【解决方案3】:

    这里的 data 是 jQuery objectObject 必须是 keyvalue 对。

    data.message = "This is the first message";
    

    【讨论】:

      【解决方案4】:

      你可以这样做:

      objObject.message = "...";
      

      将属性添加到对象的末尾会将其作为变量添加到该对象中。

      【讨论】:

        猜你喜欢
        • 2021-12-07
        • 2012-01-19
        • 2019-06-06
        • 1970-01-01
        • 1970-01-01
        • 2016-07-01
        • 2021-06-06
        • 2021-10-08
        • 1970-01-01
        相关资源
        最近更新 更多