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

如何在JavaScript中打印数组的第n个元素?附具体场景求助

问题解决思路
  • 先纠正一个小细节:pop()方法不需要传入参数,它会直接删除数组的最后一个元素,所以你写的clothes.pop("Affliction T shirt")其实和clothes.pop()作用完全一致,pop方法不接收元素参数。

  • 关于打印数组第三个元素:JavaScript数组采用零索引计数,第一个元素对应索引0,第二个对应1,第三个对应索引2。所以直接通过索引访问即可:

修改后的代码示例:

var clothes = [];
clothes.push("Jorts");
clothes.push("White Tank top");
clothes.push("Sweat Pants");
clothes.push("Sandals and sox");
clothes.push("Affliction T shirt");
clothes.pop(); // 去掉参数,效果一致

// 打印第三个元素
console.log(clothes[2]);

执行这段代码后,控制台会输出Sweat Pants,也就是你要的第三个元素。

内容的提问来源于stack exchange,提问作者Dustin Faust

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 17:12:05