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
相关产品推荐
相关产品推荐

