【问题标题】:How can I add an object into an array using javascript?如何使用 javascript 将对象添加到数组中?
【发布时间】:2016-09-11 09:17:01
【问题描述】:

我在 app.js 文件中有一个数组,如下所示:

   var data = [
                {id:1, firstName: 'John', lastName: 'Smith'},
                {id:2, firstName: 'Jane', lastName: 'Smith'},
                {id:3, firstName: 'John', lastName: 'Doe'}
              ];

现在,我正在使用 Node.js 并尝试在 module.js 文件中创建一个函数调用 addEmployee()。 addEmplyee() 只接受两个参数,被添加的名字和姓氏。 id 值应使用 underscore.js 计算为比当前最大 id 大一。 这是我在 module.js 文件中的代码,但是它不起作用。

var _ = require('underscore');
module.exports = {
    addEmployee: function (firstName, lastName) {

        function Person(id, firstName, lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
            this.id = function (data) {
                var id = _.max(data, function (data) {
                    return data.id;
                });
                return id.id + 1;
            }
            var person = new Person(id, firstName, lastName);
            data.push(person);
            return data;

        }
    }
}

有人可以帮忙吗?提前非常感谢您!

【问题讨论】:

  • @lupatus :不完全是递归的,我用错了措辞。但是当 op 再次为 person 创建对象时,当再次调用函数时,它会创建对象,对吗?

标签: javascript arrays node.js


【解决方案1】:

试试这个:

var _ = require('underscore');
module.exports = {
    addEmployee: function (firstName, lastName) {

        function Person(id, firstName, lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
            this.id = (function (data) {
                var id = _.max(data, function (data) {
                    return data.id;
                });
                return id.id + 1;
            })();    //IIFE to invoke function immidiately and thus assign value to id
            data.push({id: this.id,firstName: this.firstName,lastName: this.lastName});
            return data;

        }
    }
}

【讨论】:

  • 你好@A.J 非常感谢!但是,我没有定义。可能,我解释的不是很好。我的数据变量在另一个名为 app.js 的 js 文件中。我应该先将此数据导入 module.js 吗?如果是,我该如何在 node.js 中做到这一点?谢谢!
【解决方案2】:

首先你无论如何都不要调用这个内部函数/构造函数,因此它不会被添加到数组中。其次,不要在函数内定义Person(它会在每次调用时被定义为新事物——每个新的Person 都是新类型)。第三件事是,如果你调用你的代码,它会导致无限循环(在构造函数中对 self 调用 new 将在下一个新实例中执行相同的操作,依此类推)。此外,您在哪里定义/导入数据?

var _ = require('underscore');

// probably it'd be even better to move this to separate module
function Person(id, firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.id = id;
};

module.exports = {
    addEmployee: function (firstName, lastName) {
        data.push(new Person((_.max(data, function (data) {
            return data.id;
        }) + 1), firstName, lastName));
    }
}

我还推荐lodash 而不是undescore(直接替换,但写得更好)。


如果您只需要保存数据的对象{ id, firstName, lastName },则不需要新类型Person

module.exports = {
    addEmployee: function (firstName, lastName) {
        var id = (_.max(data, function (data) {
            return data.id;
        }) + 1);
        data.push({ id: id, firstName: firstName, lastName: lastName });
    }
}

如果您使用节点 6.X 或 4.X+(不确定 es6 表示法是否适用于所有 4.X,肯定 4.4+ 会这样做)和'use strict';,它可能会更短:

'use strict';

var _ = require('underscore');

module.exports = {
    addEmployee: function (firstName, lastName) {
        var id = (_.max(data, function (data) {
            return data.id;
        }) + 1);
        data.push({ id, firstName, lastName });
    }
}

最后,我建议不要改变数据(副作用大多很糟糕) - 我会将其转换为类似的东西(假设节点可以执行 es6):

'use strict';

const _ = require('underscore');

module.exports = {
    // note that data comes as input
    addEmployee: function (data, firstName, lastName) {
        // obtain next id
        const id = (_.max(data, function (data) {
            return data.id;
        }) + 1);
        // return new data (old data + new object, but without mutation of initial object)
        return [...data, { id, firstName, lastName }];
    }
}

【讨论】:

  • 您好@Iupatus,非常感谢您的全面解释!抱歉,我是 node.js 的新手,所以有些部分我仍然感到困惑。我还在努力理解您的回答,很快就会给您反馈。
【解决方案3】:

应该是这样的:

var _ = require('underscore');
// import data

module.exports = {
    addEmployee: function (firstName, lastName) {
        // remove id
        function Person(firstName, lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
            this.id = (function (data) {
                var id = _.max(data, function (data) {
                    return data.id;
                });
                return id.id + 1;
            })();    
        }

        // put OUTSIDE - dont need id here
        var person = new Person(firstName, lastName);
        data.push(person);
        return data;
    }
}

【讨论】:

  • 你好@Daniel Tran,非常感谢!但是,我收到一个错误: var person = new Person(id, firstName, lastName); ^ ReferenceError: id is not defined 可能,我解释的不是很好。我的数据变量在另一个名为 app.js 的 js 文件中。我应该先将此数据导入 module.js 吗?如果是,我该如何在 node.js 中做到这一点?谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-16
  • 1970-01-01
  • 1970-01-01
  • 2019-09-02
  • 2020-10-22
相关资源
最近更新 更多