【Javascript】数组练习(在排好序的数组⾥,按照⼤⼩顺序插⼊数据)

javascript 复制代码
var array=[1,4,5,7,9,17];
console.log(array);

比如要插入一个数16

javascript 复制代码
var array=[1,4,5,7,9,17];

var num=16;
var index=null;
var i;
for(i=0;i<array.length;i++){
    if(array[i]<num){
        index=i;
    }
}
console.log(index);

首先通过循环找出最后一个比自定义的num小的值,并且输出该值所在的下标,

数组的下标从0开始索引,index=4,表示第五个位置

javascript 复制代码
var array=[1,4,5,7,9,17];

var num=16;
var index=null;
var i;
for(i=0;i<array.length;i++){
    if(array[i]<num){
        index=i;
    }
}
console.log(index);
array.splice(5,0,num);
console.log(array);

或者

复制代码
array.splice(index+1,0,num);

index+1是指我们要找的最后一个比num小的元素的位置即9

index是他的下标值,

调用splice方法,从9开始截取,0表示截取0个,num是在截取的后面添加数据

具体请看:

https://blog.csdn.net/m0_67930426/article/details/133980559?spm=1001.2014.3001.5501

相关推荐
天天进步201513 小时前
Python全栈项目--基于机器学习的异常检测系统
开发语言·python·机器学习
问心无愧051320 小时前
ctf show web入门160 161
前端·笔记
xxie12379420 小时前
return与print
开发语言·python
秋920 小时前
从 Python 后端工程师转型 AI Engineer(AI 工程化)的完整补课清单(2026实战版)
开发语言·人工智能·python
李小白6620 小时前
第四天-WEB服务器基本原理,IIS服务
运维·服务器·前端
程序员二叉21 小时前
【Java】 异常高频面试题精讲 | 易错点+对比总结
java·开发语言·面试
humcomm21 小时前
AI编程时代新前端职位
前端·ai编程
好家伙VCC21 小时前
Web Components主题热切换方案揭秘
java·前端
慕木沐21 小时前
Google ADK Java 1.0版本 核心机制与实战 Demo
java·开发语言·python
Roann_seo%21 小时前
C++文件操作完全指南:从文本读写到二进制文件处理
开发语言·c++