当前位置:网站首页>js题目:输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组。
js题目:输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组。
2022-07-06 09:17:00 【阿波次嘚】
var arr34 = [1, 4, 32, 4, 5, 7, 8];//实际应输出 [32,4,8,4,5,7,1]
var arr_new_34 = [].concat(arr34);//深拷贝
arr_new_34.sort(function (a, b) {
return a > b ? 1 : -1; });//排序找出最大最小值
var max = arr_new_34[arr_new_34.length - 1];
var min = arr_new_34[0];
var maxIndex = arr34.indexOf(max);//获取最大值在原数组的下标
[arr34[0], arr34[maxIndex]] = [arr34[maxIndex], arr34[0]];//将最大值与第一个元素交换位置 -- 解构赋值
//*** 注意 如果你第一次交换位置是把最大值和最小值交换了位置 此时 最小值的下标已经改变 变成了 2 原来是 0
//所以最小值得下标得等到交换完一遍位置在获取
var minIndex = arr34.indexOf(min);//获取最小值在原数组的下标
[arr34[arr34.length - 1], arr34[minIndex]] = [arr34[minIndex], arr34[arr34.length - 1]];//将最小值与第一个元素交换位置
console.log(arr34.join(","));

边栏推荐
- Basic use of pytest
- STM32型号与Contex m对应关系
- E-commerce data analysis -- salary prediction (linear regression)
- Arduino gets the length of the array
- 数据分析之缺失值填充(重点讲解多重插值法Miceforest)
- Vert. x: A simple login access demo (simple use of router)
- FTP file upload file implementation, regularly scan folders to upload files in the specified format to the server, C language to realize FTP file upload details and code case implementation
- XML文件详解:XML是什么、XML配置文件、XML数据文件、XML文件解析教程
- RuntimeError: cuDNN error: CUDNN_STATUS_NOT_INITIALIZED
- .elf .map .list .hex文件
猜你喜欢

arduino JSON数据信息解析

JS正则表达式基础知识学习

Arm pc=pc+8 is the most understandable explanation

JS object and event learning notes

Pytorch four commonly used optimizer tests

ES6语法总结--下篇(进阶篇 ES6~ES11)

MongoDB

MySQL realizes read-write separation

uCOS-III 的特点、任务状态、启动

sklearn之feature_extraction.text.CountVectorizer / TfidVectorizer
随机推荐
Apprentissage automatique - - régression linéaire (sklearn)
STM32型号与Contex m对应关系
Missing value filling in data analysis (focus on multiple interpolation method, miseforest)
嵌入式启动流程
Programmers can make mistakes. Basic pointers and arrays of C language
Dead loop in FreeRTOS task function
Variable star user module
ES6语法总结--上篇(基础篇)
Inline detailed explanation [C language]
mysql实现读写分离
Rough analysis of map file
Detailed explanation of Union [C language]
Time slice polling scheduling of RT thread threads
MP3mini播放模块arduino<DFRobotDFPlayerMini.h>函数详解
GNN的第一个简单案例:Cora分类
RuntimeError: cuDNN error: CUDNN_STATUS_NOT_INITIALIZED
Arduino uno R3 register writing method (1) -- pin level state change
JS正则表达式基础知识学习
AMBA、AHB、APB、AXI的理解
ESP8266使用arduino连接阿里云物联网