将多个属性添加到现有js对象

编程入门 行业动态 更新时间:2024-10-27 15:18:00
本文介绍了将多个属性添加到现有js对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想为具有现有属性的现有对象添加多个属性。每个新属性是否比一行更简洁?

I want to add multiple attributes to an existing object with existing attributes. Is there a more concise way than one line per new attribute?

myObject.name = 'don'; myObject.gender = 'male';

MDN上的所有内容都显示了如何使用括号表示法创建新对象,但不显示现有对象: developer.mozilla/en-US/docs/JavaScript/Guide/ Working_with_Objects

Everything on MDN shows how to do new objects with bracket notation, but not existing objects: developer.mozilla/en-US/docs/JavaScript/Guide/Working_with_Objects

推荐答案

来自如何动态合并两个JavaScript对象的属性?

var obj2 = {name: 'don', gender: 'male'}; for (var attrname in myobject) { myobject[attrname] = obj2[attrname]; }

编辑

要有点儿更清楚如何扩展Object以使用此函数:

To be a bit clearer about how you could extend Object to use this function:

//Extend the protype so you can make calls on the instance Object.prototype.merge = function(obj2) { for (var attrname in obj2) { this[attrname] = obj2[attrname]; } //Returning this is optional and certainly up to your implementation. //It allows for nice method chaining. return this; }; //Append to the object constructor function so you can only make static calls Object.merge2 = function(obj1, obj2) { for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; } //Returning obj1 is optional and certainly up to your implementation return obj1; };

用法:

var myObject1 = { One: "One" }; myObject1.merge({ Two: "Two" }).merge({ Three: "Three" }); //myObject1 is { One: "One", Two: "Two", Three: "Three", merge: function } var myObject2 = Object.merge2({ One: "One" }, { Two: "Two" }); Object.merge2(myObject2, { Three: "Three" }); //myObject2 is { One: "One", Two: "Two", Three: "Three" }

注意:您当然可以根据需要实施灵活的合并冲突策略。

Note: You certainly could implement a flexible merge conflict strategy depending on your needs.

更多推荐

将多个属性添加到现有js对象

本文发布于:2023-07-17 10:45:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1132401.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   属性   对象   js

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!