【问题标题】:Incorrectly returning an Object?错误地返回一个对象?
【发布时间】:2017-11-20 23:19:31
【问题描述】:

我有一个如下所示的函数:

    function addProperty(object, property) {

}

我必须将属性参数的值作为键添加到对象参数。新属性的值必须设置为 null。之后,我将返回具有新添加属性的对象。预期的输入是这样的:{ x: 5 }, 'y',左边是对象,右边是属性。预期的输出是这样的:{ x: 5, y: null }

这是我目前所拥有的:

function addProperty(object, property) {
   object = { object, [property]: null};
  return object;
}

addProperty({x:5}, 'y');

这是我得到的输出:{ object: { x: 5 }, y: null }。我在这里做错了什么?我如何摆脱输出开头看起来像对象属性的东西并留下对象本身和属性??。

【问题讨论】:

  • 请注意,这样做会在您的函数范围之外编辑object。这意味着即使您不返回object,您作为参数传递的那个也会被修改。示例:addProperty(someObject, 'y') 会将y: null 添加到已经存在的对象someObject
  • 该代码在上周出现在四五个问题中。作业?
  • 抱歉,James,我认为我正确使用了搜索功能。我原来的帖子有一个警告,如果发现问题是重复的,我会删除它。不幸的是,该声明已被 Jordumus 编辑。也许该语句不适用于堆栈。代码源自类似于训练营的 Lambda 学校。请注意,我问社区他们是否知道我做错了什么,Ori 回答得很漂亮。我希望我的问题不会与“家庭作业问答问题”混淆。

标签: javascript ecmascript-6


【解决方案1】:

使用Object#assign在原来的基础上创建一个新对象,具有新的属性:

function addProperty(object, property) {
   return Object.assign({}, object, { [property]: null });
}

console.log(addProperty({x:5}, 'y'));

或者使用Object Rest/Spread proposal(需要Babel和transform):

function addProperty(object, property) {
  return { ...object, [property]: null };
}

console.log(addProperty({x:5}, 'y'));

您的代码有什么问题:

当您编写{ object } 时,您正在使用ES6 Shorthand property names 创建一个新的对象字面量,该字面量具有“object”属性和旧对象的值。实际上,您正在写作:

object = { object: object }

function addProperty(object, property) {
  object = { // assign a new object literal to the object variable
    object, // add a new property by name of "object" with the contents of the original object
    [property]: null
  };
  return object;
}

console.log(addProperty({x:5}, 'y'));

【讨论】:

    【解决方案2】:

    像这样设置对象属性:

    function addProperty(object, property) {
      object[property] =  null;
      return object;
    }
    

    【讨论】:

      【解决方案3】:

      这样设置对象的属性就可以了

      function addProperty(object, property) {
         object[property] = null
        return object;
      }
      console.log(addProperty({x:5}, 'y'));

      ES6中,Object.defineProperty()方法直接在一个对象上定义一个新的属性,或者修改一个对象上已有的属性,并返回该对象。

      function addProperty(object, property) {
      Object.defineProperty(object, property, {
       value: null,
        writable: true,
        enumerable: true,
        configurable: true
      });
        return object;
      }
      var o = {x:5};
      console.log(addProperty(o, 'y'));

      阅读更多关于它的信息here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-06
        • 2015-06-03
        • 2014-05-27
        • 2014-05-22
        相关资源
        最近更新 更多