创建我自己的arrayName.push()函数

时间:2020-05-04 21:32:53

标签: javascript

因此,我正在编写将最高分放入新数组中的代码,而我不想使用push函数。请看一下我的代码,我真的不知道要在bestSolutions [?]中添加什么,因为我希望它是一个包含最高分数的新数组。

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

}

for (var i = 0; i < scores.length; i++){
    if (scores[i] == highScore){
        bestSolutions[] = i
    }

}
console.log(bestSolutions)
console.log(highScore);

4 个答案:

答案 0 :(得分:0)

您可以使用unshift()

bestSolutions.unshift(i);

您也可以仅显式设置索引:

bestSolutions[0] = i;

答案 1 :(得分:0)

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

}

for (var i = 0; i < scores.length; i++){
    if (scores[i] == highScore){
        bestSolutions[bestSolutions.length] = i //Here the change
    }

}
console.log(bestSolutions)
console.log(highScore);

答案 2 :(得分:0)

您可以只设置最后一个索引+ 1,幸运的是数组长度:

 bestSolutions[bestSolutions.length] = i;

鉴于.push确实做到了这一点,我看不出为什么要避免它的原因。

答案 3 :(得分:-1)

从问题的角度看,您似乎正在尝试存储数组最大值的索引。

检查此链接... Return index of greatest value in an array

希望这会有所帮助!