优秀的编程知识分享平台

网站首页 > 技术文章 正文

JavaScript 数组常用操作(javascript中数组)

nanyue 2024-09-08 05:59:45 技术文章 4 ℃


join 数组转字符串,指定间隔符

var list=['a','b','c','d']

var str = list.join(",")

console.log(str)//a,b,c,d

pop 数组删除删除最后一个元素,返回删除的元素

var list=['a','b','c','d']

var p = list.pop()

console.log(p)//d

console.log(list)//['a','b','c']

shift 从数组中删除第一个元素,返回删除的元素

var s = list.shift()

console.log(s)//a

console.log(list)//['b','c']

push 数组结尾添加元素并返回新数组的长度


var list=['a','b','c']

var i = list.push('d');

console.log(i);//4

console.log(list)//['a','b','c','d']

unshift 数组开头添加元素并返回新数组的长度

var j = list.unshift('x')

console.log(j);//5

console.log(list)//['x','a','b','c','d']

splice(x,y) 第一个参数添加新元素的位置、第二个参数删除多少个元素

var list=['a','b','c']

//splice 向数组添加新元素

var a = list.splice(2, 0, "m", "n");

console.log(list)//['a','b','m','n','c']

//splice 删除元素

var list=['a','b','c']

var a = list.splice(0, 1)

console.log(a);//['a']

console.log(list)//['b','c']

concat 合并数组

var list1 = ['a','b']

var list2 = ['m','n']

var newList = list1.concat(list2)

console.log(list1)//['a','b']

console.log(newList)//['a','b','m','n']

slice 裁剪数组,返回新数组,它不会从原数组中删除任何元素

var list = ['a','b','c']

var newList = list.slice(1)

console.log(newList)//['b','c']

console.log(list)//['a','b','c']

var newList = list.slice(1,2)

console.log(newList)//['b']

console.log(list)//['a','b','c']

sort 排序,改变原数组

var points = [40, 100, 5, 25];

points.sort(function(a, b){return a - b});

console.log(points)//[5,25,40,100]

reverse 反转数组

points.reverse()

console.log(points)//[100,40,25,5]

forEach 数组遍历

var list =[1,2,3,4,5]

list.forEach(item=>{

console.log(item)

})

filter 数组过滤 ,不改变原数组,返回新数组

var nums = [45, 4, 9, 16, 25];

var over10 = nums.filter(item=>item>10)

console.log(nums)//[45, 4, 9, 16, 25]

console.log(over10)//[45, 16, 25]

some 检查某些数组值是否满足条件 返回true,false

var nums = [45, 4, 9, 16, 25];

var over10 = nums.some(item=>item>10)

console.log(over10)//true

indexOf 在数组中搜索元素值并返回其位置,没有返回-1

var nums = [45, 4, 9, 16, 25]

var idx = nums.indexOf(9)

console.log(idx)//2

var idx = nums.indexOf(10)

console.log(idx)//-1

find 返回满足条件的第一个数组元素的值,没有返回undefined

var nums = [45, 4, 9, 56, 25]

var mum = nums.find(item=>item>50)

console.log(mum)//56

findIndex 返回满足条件的第一个数组元素的索引,没有返回-1

var nums = [45, 4, 9, 56, 25]

var mum = nums.findIndex(item=>item>10)

console.log(mum)//0

最近发表
标签列表