提问人: 提问时间:3/14/2023 更新时间:3/14/2023 访问量:27
无法在 JS 中使用 reduce 生成所需的字符串
Cannot generate required string with reduce in JS
问:
我有这个错误,无法解决这个问题。我试着寻找被问到的问题,但没有一个能回答我的问题。我尝试使用代码,它看起来很简单,但令人困惑,因为我只是在学习这个。
我想输出为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,
'。
感谢您对此进行调查。
答:
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;
}));
我们需要删除检查,因为它在初始数组中不存在。我们还需要知道我们何时进行最后一次迭代,我在上面通过检查完成了and
if(index === countries.length - 1)
评论
0赞
3/14/2023
你这么多:)
评论
countries
'Nepal', 'China', 'United States'
and