You need to enable JavaScript to run this app. JavaScript中如何不使用push方法实现数组元素追加
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中如何不使用push方法实现数组元素追加

《Head First JavaScript Programming》练习:不使用 push 实现数组填充

现有如下 JavaScript 代码,通过 push 方法向空数组 bestSolutions 填充最高分对应的测试索引,练习要求:完全不使用 push 方法,实现和原代码完全一致的输出效果。

let scores = [60, 50, 60, 58, 54, 54, 58, 50, 52, 54, 48, 69, 34, 55, 51, 52, 44, 51, 69,
  64, 66, 55, 52, 61, 46, 31, 57, 52, 44, 18, 41, 53, 55, 61, 51, 44
]
var highScore = 0
var output

for (var i = 0; i < scores.length; i++) {
  output = `Bubbles solution # ${i} score: ${scores[i]}<br>`
  document.write(output)
  if (scores[i] > highScore) {
    highScore = scores[i]
  }
}
let bestSolutions = []
for (var i = 0; i < scores.length; i++) {
  if (scores[i] == highScore) {
    bestSolutions.push([i])
  }
}

document.write(`Bubbles Tests: ${scores.length}<br>`)
document.write(`Highest Bubble Score: ${highScore}<br>`)
document.write(`Solutions with highest score: #${bestSolutions[0]} and #${bestSolutions[1]}`)

实现思路

  • 数组的push方法底层逻辑是:在数组当前末尾(索引等于数组现有length的位置)插入新元素,同时将数组length自增1。
  • 直接对数组对应索引赋值,即可模拟push的行为,不需要调用push方法。

最终修改后的代码

let scores = [60, 50, 60, 58, 54, 54, 58, 50, 52, 54, 48, 69, 34, 55, 51, 52, 44, 51, 69,
  64, 66, 55, 52, 61, 46, 31, 57, 52, 44, 18, 41, 53, 55, 61, 51, 44
]
var highScore = 0
var output

for (var i = 0; i < scores.length; i++) {
  output = `Bubbles solution # ${i} score: ${scores[i]}<br>`
  document.write(output)
  if (scores[i] > highScore) {
    highScore = scores[i]
  }
}
let bestSolutions = []
for (var i = 0; i < scores.length; i++) {
  if (scores[i] == highScore) {
    // 直接利用数组自身的length作为插入索引,完全替代push逻辑
    bestSolutions[bestSolutions.length] = [i]
  }
}

document.write(`Bubbles Tests: ${scores.length}<br>`)
document.write(`Highest Bubble Score: ${highScore}<br>`)
document.write(`Solutions with highest score: #${bestSolutions[0]} and #${bestSolutions[1]}`)

效果一致性说明

  • 空数组bestSolutions初始length为0,第一次满足条件时给索引0赋值,赋值后数组length自动变为1
  • 第二次满足条件时,当前length为1,给索引1赋值,赋值后length自动变为2
  • 赋值内容和原代码push([i])完全一致,后续模板字符串输出时,单元素数组转字符串的规则也和原代码完全相同,因此最终输出没有任何差异
  • 该逻辑兼容任意数量的最高分匹配项,和原push版本的行为完全一致

内容的提问来源于stack exchange,提问作者Erin Fleming

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.12.01 12:06:05