如何解决if语句为true时,nodejs映射不返回任何内容
所以我有以下代码
data.push(commands.map(
command => {
if (!command.devOnly) { return command.name; } // first condition
if (command.devOnly && message.author.id != '3251268789058714880') {} // second condition
},).join('\n'));
如果第二个条件为true,则返回null
,但是当我运行console.log(data)
时,对于第二个条件为true的所有命令,它都有空白行。
有没有办法阻止第二个条件返回任何东西,而又不留空行
解决方法
.map()
是1对1转换,因此输出数组中的元素数与输入数组完全相同。如果您不返回任何内容,则数组中的该元素将具有一个undefined
值(当您不主动返回内容时,该值为返回值)。
要变换数组并消除某些元素,不能使用.map()
。您可以执行.filter().map()
,先过滤掉不需要的项目,然后映射其他项目,也可以使用常规的for
循环,然后将项目推入要输出的数组中继续使用常规的for
循环迭代或.reduce()
或.forEach()
迭代。
一个例子:
const results = commands.filter(command => !command.devOnly).map(command => command.name);
console.log(results);
const results = [];
for (let command of commands) {
if (!command.devOnly) results.push(command.name);
}
console.log(results);
请注意,您的第二个条件在您的代码示例中什么都不做,因此我不确定在这些示例中如何说明这一点。
P.S。我经常希望Javascript具有.filterMap()
功能,让您返回undefined
以使结果中保留该值-否则,像.map()
一样工作。但是,它没有内置的功能。您可以构建自己的功能。
根据您的评论,您可以根据以下两种条件进行过滤:
const results = commands
.filter(command => !command.devOnly || message.author.id === '3251268789058714880')
.map(command => command.name);
console.log(results);
,
您可以使用Array.reduce
commands.reduce((prev,command)=>{
if (!command.devOnly)
return [...prev,command.name]
// this if,is useless but shows that you can use more conditions.
if (command.devOnly && message.author.id != '3251268789058714880')
return prev
// add more conditions as you need here
return prev
},[])
另一种选择是通过映射然后过滤未定义的值,或使用for循环
就像jfriend00在他的回答中解释的那样。他希望可以使用filterMap()
Array.reduce
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。