今天刷题,遇到一个问题:
力扣506题:
var findRelativeRanks = function(score) {
let score1=score;
score.sort((a,b)=>b-a)
let answer =[]
for(let i=0;i<score.length;i++)
{
let index=score.indexOf(score1[i])
if(index==0)
{
answer[i]="Gold Medal";
}else if(index==1)
{
answer[i]="Silver Medal"
}else if(index==2)
{
answer[i]="Bronze Medal"
}else
{
answer[i]=(index+1).toString()
}
}
return answer
};
发现不管放入哪个例子,输出永远都是:
后来检查发现score1随着score排序而变化
所以一定要挨个赋值!!!
var findRelativeRanks = function(score) {
let score1=[];
for(let i=0;i<score.length;i++)
{
score1[i]=score[i]
}
score.sort((a,b)=>b-a)
let answer =[]
for(let i=0;i<score.length;i++)
{
let index=score.indexOf(score1[i])
if(index==0)
{
answer[i]="Gold Medal";
}else if(index==1)
{
answer[i]="Silver Medal"
}else if(index==2)
{
answer[i]="Bronze Medal"
}else
{
answer[i]=(index+1).toString()
}
}
return answer
};