为什么从定制模块导入的函数在JSfiddle中工作时行为会有所不同?

时间:2019-06-15 14:13:40

标签: node.js lodash

我有2个文件index.js和sort.js。

index.js文件包含一个变量“ x”,其值是英语单词对象的数组。每个对象都包含一个“ pos”属性,该属性又是一个数组,其值可以是n,v,adj,adv(至少包含一个值)

sort.js包含一个将变量“ x”作为其参数的函数。然后,它以这样一种方式排列单词,即每个pos值都变成主数组内部的一个单独的数组。

代码正在jsfiddle中运行,但是在我的项目中得到一个空数组作为输出。我已经尝试过在sort.js文件中使用不同的导出方法,例如module.exports等。

注意:我使用lodash作为依赖项。

这是两个文件的代码:

index.js

const _ = require("lodash");
const { sortByPos } = require("../lib/sort");

/* 
 Some extra code here
*/

let x = [
    {
      word: "music",
      pos: ["n"],
      first: "m",
      wordCount: 1,
      len: 5
    },
    {
      word: "scale",
      pos: ["n", "v"],
      first: "s",
      wordCount: 1,
      len: 5
    },
    {
      word: "beats",
      pos: ["n"],
      first: "b",
      wordCount: 1,
      len: 5
    },
    {
      word: "surmount",
      pos: ["v"],
      first: "s",
      wordCount: 1,
      len: 8
    },
    {
      word: "euphony",
      pos: ["n", "adv"],
      first: "e",
      wordCount: 1,
      len: 7
    },
    {
      word: "trounce",
      pos: ["adj", "v"],
      first: "t",
      wordCount: 1,
      len: 7
    }
  ];

  console.log(sortByPos(x))

sort.js

const _ = require("lodash");
exports.sortByPos = words => {
 return _.reduce(
 words,
 (result, obj) => {
   _.forEach(obj.pos, el => (result[el] || (result[el] = [])).push(obj));
   return result;
 },
 []
 );
};

更新:代码在JSFiddle中也无法正常工作。

1 个答案:

答案 0 :(得分:0)

您的减少累加器(result)是一个数组,但是您为其分配了非数字键。而是使用对象作为累加器,如果需要数组,请使用_.values()Object.values()将其转换为数组:

const sortByPos = words => {
  return _.reduce(
    words,
    (result, obj) => {
      _.forEach(obj.pos, el => (result[el] || (result[el] = [])).push(obj));
      return result;
    }, {}
  );
};

let x = [{"word":"music","pos":["n"],"first":"m","wordCount":1,"len":5},{"word":"scale","pos":["n","v"],"first":"s","wordCount":1,"len":5},{"word":"beats","pos":["n"],"first":"b","wordCount":1,"len":5},{"word":"surmount","pos":["v"],"first":"s","wordCount":1,"len":8},{"word":"euphony","pos":["n","adv"],"first":"e","wordCount":1,"len":7},{"word":"trounce","pos":["adj","v"],"first":"t","wordCount":1,"len":7}];

console.log(sortByPos(x)) // an object of arrays

console.log(_.values(sortByPos(x))) // an array of arrays
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>