JavaScript相关代码
第一种方法
let n = new Array(10);//创建一个十位数组
for(let i = 0; i < n.length; i++){ // 对数组填充随机数
n[i] = Math.round(Math.random()*99)+1; } console.log(n.join(","));//控制台输出
//冒泡排序核心部分
for (let i = 0; i < n.length; i++){ for (let j = 0; j < n.length-i; j++){ if(n[j] < n[j+1]){ let temp = n[j]; n[j] = n[j+1]; n[j+1] = temp; } } } console.log(n.join(","));
第二种方法(和第一种方式核心相同,只是数组的填充方式不同)
fill()方法,使用固定值填充数组
array.fill(value, start, end) value:需要填充的值 start:开始位置 end:结束位置
let n = new Array(10); n.fill(5,0,10);//填充数组 //使用map()方法数组不能为空(实际上是数组中元素的替换)
let na = n.map(()=>Math.round(Math.random()*99)+1); console.log(na.join(",")); for (let i = 0; i < na.length; i++){ for (let j = 0; j < na.length-i; j++){ if(na[j] < na[j+1]){ let temp = na[j]; na[j] = na[j+1]; na[j+1] = temp; } } } console.log(na.join(","));