gpt4 book ai didi

node.js - 为什么从定制模块导入的函数在 JSfiddle 中工作时表现不同?

转载 作者:太空宇宙 更新时间:2023-11-04 01:29:08 25 4
gpt4 key购买 nike

我有 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))

排序.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 中也无法正常工作。

最佳答案

您的reduce累加器(结果)是一个数组,但您为其分配非数字键。相反,使用对象作为累加器,如果需要数组,请使用 _.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>

关于node.js - 为什么从定制模块导入的函数在 JSfiddle 中工作时表现不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56611139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com