当前位置:网站首页>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]) } } }
边栏推荐
- vs2019 第一个MFC应用程序
- [蓝桥杯2017初赛]包子凑数
- Windows下安装MongDB教程、Redis教程
- Armv8-a programming guide MMU (2)
- JDBC原理
- [ahoi2009]chess Chinese chess - combination number optimization shape pressure DP
- PyCharm中无法调用numpy,报错ModuleNotFoundError: No module named ‘numpy‘
- [蓝桥杯2021初赛] 砝码称重
- When you open the browser, you will also open mango TV, Tiktok and other websites outside the home page
- AcWing 1294. Cherry Blossom explanation
猜你喜欢

Integration test practice (1) theoretical basis

Use dapr to shorten software development cycle and improve production efficiency

Face recognition_ recognition

02 staff information management after the actual project

One click extraction of tables in PDF

Install mongdb tutorial and redis tutorial under Windows

QT creator specify editor settings

LeetCode #461 汉明距离

Vs2019 use wizard to generate an MFC Application

安装numpy问题总结
随机推荐
保姆级出题教程
Django运行报错:Error loading MySQLdb module解决方法
AcWing 179. Factorial decomposition problem solution
QT creator shape
Record a problem of raspberry pie DNS resolution failure
Asp access Shaoxing tourism graduation design website
Solution to the practice set of ladder race LV1 (all)
vs2019 桌面程序快速入门
About string immutability
Learning question 1:127.0.0.1 refused our visit
Introduction to the easy copy module
LeetCode #461 汉明距离
Dotnet replaces asp Net core's underlying communication is the IPC Library of named pipes
牛客Novice月赛40
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
Error reporting solution - io UnsupportedOperation: can‘t do nonzero end-relative seeks
數據庫高級學習筆記--SQL語句
MySQL主從複制、讀寫分離
[ahoi2009]chess Chinese chess - combination number optimization shape pressure DP
Summary of numpy installation problems