当前位置:网站首页>jS数组+数组方法重构
jS数组+数组方法重构
2022-07-06 09:15:00 【进阶日记】
javaScript数组和数组方法重构
1. 数组创建
1. 字面量方法
var arr = ['1','2']
2. 函数构造方法
var arr = new Array('a','b')
2. 数组访问
数组变量名加 [索引]
var arr = ['1','2'];
console.log(arr[0])
3. 数组API方法
toString()在默认情况下都会以逗号分隔字符串的形式返回数组项
join()使用指定的字符串用来分隔数组字符串
var arr = [1,5,2,8,10,{ a:1}]; console.log(arr);//[ 1, 5, 2, 8, 10, { a: 1 } ] console.log(arr.toString());//”1,5,2,8,10,[object Object]” console.log(arr.join(""));//”152810[object Object]”
Array.isArray() 用来判断某个变量是否是一个数组对象
Array.from()从类数组对象或者可迭代对象中创建一个新的数组实例
Array.of() 根据一组参数来创建新的数组实例,支持任意的参数数量和类型
var arr = Array.from("abc"); Array.isArray(arr)//true console.log(arr); //输出结果为["a","b","c"] Array.of(1, 2, 3); // [1, 2, 3]
Array.prototype.push() 向数组的末尾添加一个或多个元素,并返回新的长度
Array.prototype.pop()用于删除数组的最后一个元素并返回删除的元素
Array.prototype.shift()用于把数组的第一个元素从其中删除,并返回第一个元素的值
Array.prototype.unshift()向数组的开头添加一个或更多元素,并返回新的长度
//函数分开运行的结果 var arr = ['zs','ls','ww']; // push() 在末尾添加元素 arr.push('123');//['zs','ls','ww','123'] // pop() 删除最后一个元素,返回删除元素 arr.pop();//['zs','ls'] // shift 删除第一个元素,返回删除元素 arr.shift();//['ls','ww']; // unshift 在第一个添加元素 arr.unshift('23')//['23','zs','ls','ww'];
Array.prototype.reverse()用于颠倒数组中元素的顺序
var arr = ['zs','ls','ww']; arr.reverse()//['ww','ls','zs']
Array.prototype.sort()对数组元素进行排序,不传参默认升序
//降序 var arr = [40,100,1,5,25,10]; arr.sort(function(a,b){ return b-a });
Array.prototype.concat()用于连接两个或多个数组
array1.concat(array2,array3,...,arrayX)
Array.prototype.slice()从已有的数组中返回选定的元素
//slice(start,end) var arr = ["a", "b", "c", "d", "e"]; var result = arr.slice(1,3);//b,c
Array.prototype.splice()用于添加或删除数组中的元素
//参数一为从何开始 参数二为删除的元素个数 参数三开始为添加的元素 var arr = ["a", "b", "c", "d"]; arr.splice(2,0,"e","f");//a,b,e,f
Array.prototype.indexOf()返回数组中某个指定的元素位置
var arr = ["Banana", "Orange", "Apple", "Mango"]; var a = arr.indexOf("Apple",0);//从0号位开始查找 返回2
Array.prototype.lastIndexOf()返回一个指定的元素在数组中最后出现的位置,从后向前查
var arr = ["Banana", "Orange", "Apple", "Mango"]; var a = arr.lastIndexOf("Apple",0);//从0号位开始查找 返回2
Array.prototype.every()检测数组所有元素是否都符合指定条件
var ages = [32, 33, 16, 40]; var result = ages.every(function (age) { return age >= 18 }) console.log(result);//输出结果为:false
Array.prototype.some()检测数组中的元素是否满足指定条件
var ages = [32, 33, 16, 40]; var result = ages.some(function (age) { return age >= 18 }) console.log(result);//输出结果为:true
Array.prototype.filter()创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素
var ages = [32, 33, 16, 40]; var result = ages.filter(function (age) { return age >= 18 }) console.log(result);//输出结果为:[ 32, 33, 40 ]
Array.prototype.map()返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值
var numbers = [4, 9, 16, 25]; var result = numbers.map(function (number) { return Math.sqrt(number) }) console.log(result);//输出结果为:[ 2, 3, 4, 5 ]
Array.prototype.forEach()调用数组的每个元素,并将元素传递给回调函数
var age = [35,21,32,51]; age.forEach(function (item,index) { console.log(item,index); }) //35 0 //21 1 //32 2 //51 3
4. 数组方法重构
push方法重构
var arr = new Array(); arr = ['123', '24', '214', 124]; //两个方式 // Array.prototype.myPush = function (str) { // if (str == null) { // return this.length; // } else { // this[this.length] = str; // } // return this.length; // } Array.prototype.myPush = function (str) { for (let i = 0; i < arguments.length; i++) { this[this.length] = arguments[i]; } return this.length; } // arr.myPush('12'); // console.log(arr);
pop方法重写
Array.prototype.myPop = function () { if (this.length==0) { return undefined; } let temp = this[this.length - 1] this.length--; return temp; } // arr.myPop() // console.log(arr.myPop());
shift方法重写
Array.prototype.myShift = function () { let temp = this[0]; for (let i = 0; i < this.length; i++) { this[i] = this[i + 1]; } this.length = this.length - 1 return temp; } // arr.myShift() // console.log(arr);
unshift方法重写
var aa = [123, 124, 125] Array.prototype.myUnShift = function () { var result = this.length + arguments.length; for (let i = result; i > 0; i--) { if (i > arguments.length) { this[i - 1] = this[i - 1 - arguments.length] } else { this[i - 1] = arguments[i - 1] } } return result; } // aa.myUnShift('13','666','wrw',123) // console.log(aa);
reverse方法重写
Array.prototype.myReverse = function () { var arr = []; for (let j = 0; j < this.length; j++) { arr[j] = this[j]; } for (let i = 0; i < this.length; i++) { this[i] = arr[this.length - i - 1]; } return this; }
concat方法重写
Array.prototype.myConcat = function (str) { let arr = []; for (let o = 0; o < this.length; o++) { arr[o] = this[o] } if (str == '') { return arr; } for (let x = 0; x < arguments.length; x++) { if (Array.isArray(arguments[x])) { for (let i = 0; i < arguments[x].length; i++) { arr[arr.length] = arguments[x][i] } } else if (!Array.isArray(arguments[x])) { arr[arr.length] = arguments[x] } } return arr; } var q = [123, 53, 1] var x = abc.myConcat('c', q, 'd', q) // console.log(x,abc);
slice方法重写
Array.prototype.mySlice = function (start, end) { let arr = []; if (start > end && end != '') { return this; } else { if (start < 0) { start = this.length + start; } if (end < 0) { end = this.length + end; } if (end == null) { console.log(123); for (let i = start; i < this.length; i++) { arr[i - start] = this[i]; } } else { if (end > this.length) { end = this.length; } for (let j = start; j < end; j++) { arr[j - start] = this[j]; } } } return arr; } // console.log(abc.mySlice(2,4));
forEach重构
Array.prototype.myForEach=function(fun) { for (let i = 0; i < arr.length; i++) { fun(this[i],i,this) } }
every方法重写 方法中的this指向global不指向调用数组 第二个参数修改this指向
Array.prototype.myEvery = function (fun,obj) { for (let i = 0; i < this.length; i++) { if(!(obj?fun.bind(obj)(this[i]):fun(this[i]))){ return false; } } return true; }
some方法重构
Array.prototype.mySome = function (fun,obj) { for (let i = 0; i < this.length; i++) { if((obj?fun.bind(obj)(this[i]):fun(this[i]))){ return true; } } return false; } var result = qq.mySome(function(item) { return item<0 })
map方法重构
Array.prototype.myMap = function(fun,obj) { let arr = []; for (let i = 0; i < this.length; i++) { arr.push(obj?fun.bind(obj)(this[i]):fun(this[i])) } return arr; }
filter方法重构
Array.prototype.myFilter = function(fun,obj) { var result = []; for (let i = 0; i < this.length; i++) { if (obj?fun.bind(obj)(this[i]):fun(this[i])) { result.push(this[i]) } } }
边栏推荐
- [蓝桥杯2017初赛]方格分割
- DICOM: Overview
- Mtcnn face detection
- Learning question 1:127.0.0.1 refused our visit
- Codeforces Round #771 (Div. 2)
- When using lambda to pass parameters in a loop, the parameters are always the same value
- Django running error: error loading mysqldb module solution
- 数数字游戏
- LeetCode #461 汉明距离
- Codeforces Round #753 (Div. 3)
猜你喜欢
Image recognition - pyteseract TesseractNotFoundError: tesseract is not installed or it‘s not in your path
double转int精度丢失问题
QT creator test
Kept VRRP script, preemptive delay, VIP unicast details
Why can't I use the @test annotation after introducing JUnit
02 staff information management after the actual project
Introduction and use of automatic machine learning framework (flaml, H2O)
Pytorch基础
Solve the problem of installing failed building wheel for pilot
MySQL and C language connection (vs2019 version)
随机推荐
Punctual atom stm32f103zet6 download serial port pin
數據庫高級學習筆記--SQL語句
Armv8-a programming guide MMU (2)
Face recognition_ recognition
Why can't I use the @test annotation after introducing JUnit
PyCharm中无法调用numpy,报错ModuleNotFoundError: No module named ‘numpy‘
C语言读取BMP文件
ImportError: libmysqlclient. so. 20: Cannot open shared object file: no such file or directory solution
Summary of numpy installation problems
[蓝桥杯2017初赛]包子凑数
QT creator shape
基于apache-jena的知识问答
Request object and response object analysis
Image recognition - pyteseract TesseractNotFoundError: tesseract is not installed or it‘s not in your path
Introduction to the easy copy module
Remember the interview algorithm of a company: find the number of times a number appears in an ordered array
引入了junit为什么还是用不了@Test注解
记一次某公司面试题:合并有序数组
[蓝桥杯2021初赛] 砝码称重
MySQL主從複制、讀寫分離