1

我正在处理一个保存到 mongodb 数据库存储的 javascript(node.js) 示例。

我遇到了一段代码,我不太明白本教程的作者到底想做什么以及为什么。这只是我缺乏理解,但我真的很想知道这里发生了什么。请参阅下面的代码以及我在相关行旁边的评论:

  //save new employee
  EmployeeProvider.prototype.save = function(employees, callback) {
      this.getCollection(function(error, employee_collection) {
        if( error ) callback(error)
        else {

          // This is the portion I have a question on. 
          // So this is checking to see if the array.length is undefined? Why would the length property be undefined?
          if( typeof(employees.length)=="undefined")
            // What is going on here exactly? 
            // It looks like he is initializing and array with employees parameter that was passed in to the save 
            // function earlier? I've never seen this kind of thing done before. Thoughts?
            employees = [employees];

          for( var i =0;i< employees.length;i++ ) {
            employee = employees[i];
            employee.created_at = new Date();
          }

          employee_collection.insert(employees, function() {
            callback(null, employees);
          });
        }
      });
  };

谢谢你的帮助!

克里斯

4

2 回答 2

3

看起来意图允许employees参数是单个员工或员工数组。如果传递了一个员工对象,它会变成一个单元素数组。

于 2013-05-24T14:31:41.220 回答
3

if语句及其内容(它下面的第一行)基本上说:“如果employees不是数组,则创建一个具有该名称的新数组,其中包含传入的内容”。这保证了从那时起,employees它将是一个数组。

于 2013-05-24T14:32:11.973 回答