当前位置:网站首页>JS Title: input array, exchange the largest with the first element, exchange the smallest with the last element, and output array.
JS Title: input array, exchange the largest with the first element, exchange the smallest with the last element, and output array.
2022-07-06 12:13:00 【Aboci Bang】
var arr34 = [1, 4, 32, 4, 5, 7, 8];// Actual output [32,4,8,4,5,7,1]
var arr_new_34 = [].concat(arr34);// Deep copy
arr_new_34.sort(function (a, b) {
return a > b ? 1 : -1; });// Sort to find the maximum and minimum value
var max = arr_new_34[arr_new_34.length - 1];
var min = arr_new_34[0];
var maxIndex = arr34.indexOf(max);// Get the maximum value in the subscript of the original array
[arr34[0], arr34[maxIndex]] = [arr34[maxIndex], arr34[0]];// Swap the maximum value with the first element -- Deconstruct assignment
//*** Be careful If the first time you exchange positions is to exchange the maximum and minimum positions here The subscript of the minimum value has changed Turned into 2 Turned out to be 0
// So the subscript of the minimum value has to wait until the position is obtained after the exchange
var minIndex = arr34.indexOf(min);// Get the minimum value in the subscript of the original array
[arr34[arr34.length - 1], arr34[minIndex]] = [arr34[minIndex], arr34[arr34.length - 1]];// Swap the minimum value with the first element
console.log(arr34.join(","));
边栏推荐
猜你喜欢
Classification, understanding and application of common methods of JS array
【ESP32学习-1】Arduino ESP32开发环境搭建
ES6 grammar summary -- Part 2 (advanced part es6~es11)
Basic use of pytest
Apprentissage automatique - - régression linéaire (sklearn)
Learning notes of JS variable scope and function
Comparison of solutions of Qualcomm & MTK & Kirin mobile platform USB3.0
几个关于指针的声明【C语言】
[esp32 learning-2] esp32 address mapping
Custom view puzzle getcolor r.color The color obtained by colorprimary is incorrect
随机推荐
优先级反转与死锁
【ESP32学习-2】esp32地址映射
Redis based distributed locks and ultra detailed improvement ideas
ESP学习问题记录
Missing value filling in data analysis (focus on multiple interpolation method, miseforest)
Learning notes of JS variable scope and function
uCOS-III 的特点、任务状态、启动
Knowledge summary of request
Pytorch实现简单线性回归Demo
I2C bus timing explanation
Comparaison des solutions pour la plate - forme mobile Qualcomm & MTK & Kirin USB 3.0
MySQL takes up too much memory solution
Use of lists
Characteristics, task status and startup of UCOS III
Dead loop in FreeRTOS task function
Arduino get random number
锂电池基础知识
Mysqldump error1066 error solution
JS正则表达式基础知识学习
ESP8266通过arduino IED连接巴法云(TCP创客云)