思路1:这个思路太复杂了,运行起来耗性能,就是找到数组中最大的把他踢出去形成一个新的数组,再在新的数组中把最大的踢出去,形成一个新的数组,然后再找最大的就是第三个大的,不仅把方法写死了而且超复杂
javascript">// 找出素组中第三大的
const str=[12,23,56,852,45,32,125,235,121,12,12,23,32,12,55,852]
let max=0
let max2=0
let max3=0
for(let i=0;i<str.length;i++){
if(str[i]>max){
max=str[i]
}
}
const newstr=str.filter((a)=>{
return a!==max
})
for(let i=0;i<newstr.length;i++){
if(newstr[i]>max2){
max2=newstr[i]
}
}
newstr2=newstr.filter((a)=>{
return a!==max2
})
for(let i=0;i<newstr2.length;i++){
if(newstr2[i]>max3){
max3=newstr2[i]
}
}
console.log(max3);
思路2:
1.sort()函数能把数组重大到小或者从小到大排列 arr.sort(function(a,b){return b-a})是重大到小arr.sort(function(a,b){return b-a})是从小到大
2.sort排好序列之后然后查重,遍历这个数组,当让当前这个数组不等于下一个时就他把添加到新的数组中
3.新的数组就是从大到小排列并且没用重复的数组
javascript">//找到数组中第三大的
const str=[12,23,56,852,45,32,125,235,121,12,12,23,32,12,55,852]
let newstr= str.sort(function(a,b){return b-a})
let laststr=[]
for(let i=0;i<newstr.length;i++){
if(newstr[i]!==newstr[i+1]){
laststr.push(newstr[i])
}
}
console.log(laststr[2]);