无法在 JS 中使用 reduce 生成所需的字符串

Cannot generate required string with reduce in JS

提问人: 提问时间:3/14/2023 更新时间:3/14/2023 访问量:27

问:

我有这个错误,无法解决这个问题。我试着寻找被问到的问题,但没有一个能回答我的问题。我尝试使用代码,它看起来很简单,但令人困惑,因为我只是在学习这个。
我想输出为
Nepal, China and the United States

我有这个代码:

import { countries } from "./data.js";
console.log(countries.reduce((x='',country)=>{
   if(!x.includes('and')){ 
/*array does not contain and & we need    
terminate if statement for the last value of x.*/
    x += (country +", ")
   }else{
    x +=(' and the ' + country)
   }
   return x;
}))

Countries 是一个数组
['Nepal','China','United States'],我得到的输出是:“NepalChina, United States,

'。
感谢您对此进行调查。
JavaScript 数组函数 回调

评论

0赞 VLAZ 3/14/2023
如果字符串不包含“and”,则添加逗号。但是,您实际上从未以这种方式添加“and”,因为为了添加它,它必须存在。
1赞 Portal 3/14/2023
实际包含什么?countries
0赞 3/14/2023
@VLAZ明白了,我确实注意到我在那里设置了一些错误的条件,但你能帮我获得所需的输出吗?
0赞 3/14/2023
@Portal'Nepal', 'China', 'United States'
0赞 Portal 3/14/2023
所以它们都不包含and

答:

0赞 Portal 3/14/2023 #1

let countries = ['Nepal','China','United States'];
console.log(countries.reduce((x, country, index, countries) => {
  if(index === countries.length - 1)
    return x += ', and ' + country;
  else
    return x += ', ' + country;
}));

我们需要删除检查,因为它在初始数组中不存在。我们还需要知道我们何时进行最后一次迭代,我在上面通过检查完成了andif(index === countries.length - 1)

评论

0赞 3/14/2023
你这么多:)