这是一些JavaScript数组的初始化,为什么?

我正在通过一个保存到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); }); } }); }; 

谢谢你的帮助!

克里斯

if语句和它的内容(下面的第一行)基本上是这样说的:“如果employees不是一个数组,则创build一个包含所传入内容的新数组”。 这就保证了从这一刻起, employees将成为一个arrays。

看起来像允许employees参数成为单个员工或一系列员工的意图。 如果一个员工对象被传递,它将变成一个元素数组。