You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript将《程序员的悲歌》四段诗句按逆序输出?

解决方案

问题原因

你当前的写法是将所有诗句拼接为单个长字符串后拆分字符反转,得到的是单个字符倒序的结果,不符合「整首诗按行逆序输出」的需求。

实现方法

你可以先将每一行诗句作为独立元素存入数组,反转数组的元素顺序后逐行打印即可:

// 把每行诗句存入数组,顺序和原诗一致
const verses = [
  'I really hate this damned machine',
  'I wish that they would sell it.',
  'It never does quite what I want',
  'But only what I tell it.'
]

// 反转数组顺序,得到行逆序的结果
const reversedVerses = verses.reverse()

// 逐行打印每一句
reversedVerses.forEach(line => console.log(line))

如果要求必须手动写每一行console.log语句,直接调整打印顺序即可:

console.log('But only what I tell it.');
console.log('It never does quite what I want');
console.log('I wish that they would sell it.');
console.log('I really hate this damned machine');

两种写法最终的输出结果都是:

But only what I tell it.
It never does quite what I want
I wish that they would sell it.
I really hate this damned machine

内容的提问来源于stack exchange,提问作者Raquel Lima

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 13:54:04