其他分享
首页 > 其他分享> > js的数组操作方法大全

js的数组操作方法大全

作者:互联网

js中数组的操作方法大全


常见的一些数组操作
push,pop,unshift,shift

push

var arr = [1,2,3,4];
var a = arr.push(9,8,7);
console.log(a,arr);   //1,2,3,4,9,8,7;

unshift

var arr = [1,2,3,4];
var a = arr.unshift(9,8,7);
console.log(a,arr);  //9,8,7,1,2,3,4;

pop

var arr = [1,2,3,4];
var a = arr.pop();
console.log(a,arr)    //4:  1,2,3

shift

var arr = [1,2,3,4];
var a = arr.shift();
console.log(a,arr)    //1: 2,3,4,

slice

var fruits = ["Banana","Orange","Apple","Mango"];
var citrus = fruits.splice(1,3);
console.log(citrus)   //Orange,Lemon

splice

var fruits = ["Banana","Orange","Apple","Mango"];
fruits.splice(2,2);
console.log(fruits);      //Banana,Orange

reverse


var fruits = ["Banana","Orange","Apple","Mango"];
fruits.reverse();
console.log(fruits);   //Mango,Apple,Orange,Banana

sort

var Array = [1,2,3,4,5];
var fruits = Array.sort(function(a,b) {
	//return a - b;    //从小到大
	return b - a;      //从大到小
}

join

var arr = [1,2,3,4]
var bbc = arr.join()
console.log(bbc)     //1,2,3,4

concat

var arr = [1,2,3,4];
arr.concat([5,6,7])    //[1,2,3,4,5,6,7]

indexOf()

var arr = [1,2,3,4];
arr.indexOf(1)   //0
arr.indexOf(5)   //-1

forEach()

var arr = [1,2,3,4,5];
arr.forEach((item,index,arr) =>{
	//item  为当前数组元素
	//index 为当前索引
	//arr 为数组名称
})

map()


var arr = [1,2,3,4,5,6];
arr.map(function(item,index,arr){
	return item * 2
})
//输出[2,4,6,8,10,12]

filter()

var ages = [32,33,16,40];

function checkAdult(age) {
	return age >= 18;
	//返回数组ages中所有元素大于18的元素
}

function myFunction(){
	document.getElementById("demo").innerHTML = ages.filter(checkAdult);
}
//输出结果为:32,33,40

Array.from()

let json = {
	'0':'hello',
	'1':'123',
	'2':'panda',
	length:3
}
let arr = Array.from(json);
console.log(arr);
//打印:{"hello","123","panda"}

Array.of()

let arr1 = Array.of('你好','hello');
console.log(arr1);
//{'你好','hello'}

includes()

['a','b','c','d'].includes('b')
//true
['a','b','c','d'].includes('b',1)
//true
['a','b','c','d'].includes('b',2)
//fasle

tips:includes与indexOf的区别是:前者返回布尔值(利于if条件判断),后者返回数值


参考资料:
https://www.cnblogs.com/cauliflower/p/11267809.html

标签:返回,arr,示例,操作方法,js,参数,数组,var,大全
来源: https://www.cnblogs.com/HuangJiaZ/p/16655443.html