JavaScript array deduplication/search/insertion/deletion methods

一个新手
Release: 2017-10-26 10:06:04
Original
1940 people have browsed it

Array deduplication

Prototype method

//---------------first--------------- Array.prototype.distinct = function(){ var arr=[]; var obj={}; //对象承接 for(var i=0,len=this.length;i
        
Copy after login

Common method

function removeRepeat(arr){    var array=[];    var obj={};    for(var i=0,len=arr.length;i
        
Copy after login

Array search

Sequential search

function SequenceSearch(arr, value){ var i; for(i=0; i
        
Copy after login

Binary search

Binary search elements must be in order. If they are unordered, sorting operation must be performed first

-------------折半查找-------------- function BinarySearch1(arr, value){ var low, high, mid; low = 0; high = arr.length-1; while(low<=high){ mid = Math.floor((low+high)/2); if(a[mid]==value){ return mid; } if(a[mid]>value){ high = mid-1; } if(a[mid]value){ return BinarySearch2(arr, value); } if(a[mid]
        
Copy after login

Array insertion

Sequential insertion

//----------------first---------------- function Insert(arr, n, data){ //若插入数据位置不在表尾 if (n < arr.length){ //将要插入位置之后元素依次向后移动一位 for (var i = seqList.ListLen - 1; i >= n; i--) { seqList.ListData[i + 1] = seqList.ListData[i]; } } //将数据插入到位置为n的位置并将数组的长度加1 seqList.ListData[n-1] = data; seqList.ListLen++; return true; } //----------------second---------------- function aa(arr, val) { for (var i = 0; i  -1) { arr.splice(index, 1); } }; var emp = ['abs','dsf','sdf','fd'] bb(emp, 'fd');
Copy after login

Array deletion

function Delete(arr, n){ //判断数组是否为空 if (seqList.ListLen == 0) return false; //判断n的位置是否合法 if (n < 1 || n > seqList.ListLen) return false; //如果删除不是最后位置 if (n < seqList.ListLen) { //将删除位置后继元素依次前移 for (int i = n; i < seqList.ListLen; i++) { seqList.ListData[i-1] = seqList.ListData[i]; } } //表长减1 seqList.ListLen--; return true; }
Copy after login

The above is the detailed content of JavaScript array deduplication/search/insertion/deletion methods. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!