【问题标题】:What to use instead of push?用什么代替推送?
【发布时间】:2020-08-16 21:22:22
【问题描述】:

在下面的代码中,我使用“push”来填充和清空数组。我需要帮助来编写上面的代码,以便它以相同的方式出现,而不使用“push”。 《Head First JavaScript Programming》一书向我提出了挑战。我试过了,但我很难过。

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]}`)

【问题讨论】:

  • filter + map?
  • 只需使用bestSolutions[bestSolutions.length] = [i](或相同的计数器)

标签: javascript arrays push


【解决方案1】:

如果我理解正确,您希望在一个数字数组中找到所有最大值。如果是这种情况,您可以使用reducefilter 方法来替代使用push

function findMaxes(arr) {
    const max = Math.max.apply(null, arr);
    return arr.filter(n => n == max);
}

例如:

findMaxes([3, 5, 1, 1, 4, 5]) == [5, 5]
findMaxes([-1, -1, -1]) == [-1, -1, -1]

如果要查找所有最大值的位置:

function findAllMaxPositions(arr) {
    const max = Math.max.apply(null, arr);
    return arr.map((e, index) => [e, index])
              .filter(pair => pair[0] == max)
              .map(e => e[1]);
}

【讨论】:

  • 这对我没有帮助,因为我想要返回的是项目的位置,而不是项目的值。您对我如何获得物品的位置有任何想法吗?
  • 刚刚更新了我的答案,包括如何获得职位。希望这会有所帮助!
  • 小建议。这里不需要array.reduce。试试Math.max.apply(null, arr)
  • @kingkupps 我已经添加了原始帖子的参考链接,在我的回答中建议了这个解决方案。你可以检查一下
【解决方案2】:

你可以试试这个方法:

  • 使用Math.max.apply 查找最高分。
  • 使用循环查找所有匹配值并存储它们的索引。

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 = Math.max.apply(null, scores)
var bestSolutions = scores.reduce((acc, score, index) =>
  score === highScore ? [ ...acc, index] : acc, []
);

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]}`)

基于算法:

  • 创建 2 个变量,highScorebestSolutions

  • 遍历数组。

  • 对于每次迭代,进行 2 次检查:

  • 如果当前score 大于highScore

    • 如果是,用当前分数初始化highScore,用当前索引初始化bestSolutions
  • 如果highScore 等于当前score

    • 如果是,将索引推送到当前bestSolutions

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 ];

let highScore = 0;
let bestSolutions = [];

for(let i = 0; i< scores.length; i++) {
  if (scores[i] > highScore) {
    highScore = scores[i];
    bestSolutions = [ i ];
  } else 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]}`)

参考:

【讨论】:

    【解决方案3】:

    好的,一种方法如下:如果您希望 bestscores 数组包含 scores 中等于 highscore 的元素的索引,您可以将 bestcores 定义为 ma​​p scores 通过接受元组 (value,index) 的函数,如果 value == highscore 则返回 index 否则 null

    地图示例

    const a = [2, 3, 5, 0, 6];
    
    const b = a.map(value => value * 2); // [4, 6, 10, 0, 12];
    const c = a.map((value, index) => index); //[0, 1, 2, 3, 4];
    const d = a.map((value, index) => value + index); //[2, 4, 7, 3, 10];
    
    const e = a.map((value,index) => value >= 3 ? index : null);
    // [null, 1, 2, null, 4]. We can deal with those nulls with a filter
    const f = e.filter(value => value != null) // [1,2,4]
    

    就你而言

    const highscores = scores.map((value,index) => value == highscore ? index : null)
      .filter(value => value != null);
    

    这为您提供了一种高级方法,但计算效率有点低,因为它实际上对scores 数组进行了两次迭代。手动迭代您的数组和 push 实际上效率更高。

    【讨论】:

    • 实际上,这对我来说没有意义,因为我想要返回的是项目的位置,而不是项目的价值。上述解决方案返回值。
    • 好的,在这种情况下,您可以结合使用地图和过滤器。我正在编辑我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-19
    • 2013-11-04
    • 2018-06-18
    • 2021-11-26
    • 1970-01-01
    相关资源
    最近更新 更多