当前位置:网站首页>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,cArray.prototype.splice()用于添加或删除数组中的元素
//参数一为从何开始 参数二为删除的元素个数 参数三开始为添加的元素 var arr = ["a", "b", "c", "d"]; arr.splice(2,0,"e","f");//a,b,e,fArray.prototype.indexOf()返回数组中某个指定的元素位置
var arr = ["Banana", "Orange", "Apple", "Mango"]; var a = arr.indexOf("Apple",0);//从0号位开始查找 返回2Array.prototype.lastIndexOf()返回一个指定的元素在数组中最后出现的位置,从后向前查
var arr = ["Banana", "Orange", "Apple", "Mango"]; var a = arr.lastIndexOf("Apple",0);//从0号位开始查找 返回2Array.prototype.every()检测数组所有元素是否都符合指定条件
var ages = [32, 33, 16, 40]; var result = ages.every(function (age) { return age >= 18 }) console.log(result);//输出结果为:falseArray.prototype.some()检测数组中的元素是否满足指定条件
var ages = [32, 33, 16, 40]; var result = ages.some(function (age) { return age >= 18 }) console.log(result);//输出结果为:trueArray.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]) } } }
边栏推荐
- Ansible practical Series III_ Task common commands
- L2-004 这是二叉搜索树吗? (25 分)
- 安装numpy问题总结
- QT creator custom build process
- Vs2019 desktop app quick start
- 误删Path变量解决
- Ansible practical Series II_ Getting started with Playbook
- Rhcsa certification exam exercise (configured on the first host)
- Machine learning notes week02 convolutional neural network
- [number theory] divisor
猜你喜欢
Reading BMP file with C language

double转int精度丢失问题
![[蓝桥杯2017初赛]方格分割](/img/e9/e49556d0867840148a60ff4906f78e.png)
[蓝桥杯2017初赛]方格分割

安装numpy问题总结

MySQL与c语言连接(vs2019版)

AcWing 1298. Solution to Cao Chong's pig raising problem

人脸识别 face_recognition

自动机器学习框架介绍与使用(flaml、h2o)

解决安装Failed building wheel for pillow

error C4996: ‘strcpy‘: This function or variable may be unsafe. Consider using strcpy_s instead
随机推荐
Are you monitored by the company for sending resumes and logging in to job search websites? Deeply convinced that the product of "behavior awareness system ba" has not been retrieved on the official w
Leetcode 461 Hamming distance
软件测试-面试题分享
Learn winpwn (2) -- GS protection from scratch
Install mysql5.5 and mysql8.0 under windows at the same time
Nanny level problem setting tutorial
How to set up voice recognition on the computer with shortcut keys
One click extraction of tables in PDF
Swagger, Yapi interface management service_ SE
报错解决 —— io.UnsupportedOperation: can‘t do nonzero end-relative seeks
Learn winpwn (3) -- sEH from scratch
Deoldify项目问题——OMP:Error#15:Initializing libiomp5md.dll,but found libiomp5md.dll already initialized.
[蓝桥杯2017初赛]方格分割
Number game
Some notes of MySQL
基于apache-jena的知识问答
01 project demand analysis (ordering system)
MySQL master-slave replication, read-write separation
MySQL与c语言连接(vs2019版)
Remember the interview algorithm of a company: find the number of times a number appears in an ordered array