push,unshift(当前数组改变,返回值为添加完数组的长度)
var arr = [1,2,3]
var arr1 = arr.push(4)
console.log('arr',arr)//[1,2,3,4]
console.log('arr1',arr1) // 4
var arr = [1,2,3]
var arr1 = arr.unshift(0)
console.log('arr',arr)//[0,1,2,3]
console.log('arr1',arr1) // 4
pop,shift(当前数组改变,返回值为被删除元素)
var arr = [1,2,3]
var arr1 = arr.pop()
console.log('arr',arr)//[1,2]
console.log('arr1',arr1) // 3
var arr = [1,2,3]
var arr1 = arr.shift()
console.log('arr',arr)//[2,3]
console.log('arr1',arr1) // 1
splice(i,n)(当前数组改变,返回值为被删除元素)
删除从下标i开始的n个元素
var arr = [1,2,3,4,5]
var arr1 = arr.splice(1,2)
console.log('arr',arr)//[1,4,5]
console.log('arr1',arr1) // [2,3]
concat(原数组不变,返回新数组)
var arr = [1,2,3,4,5]
var arr1 = [9,0]
arr2 = arr.concat(arr1)
console.log('arr',arr)// [1,2,3,4,5]
console.log('arr1',arr1) //[9,0]
console.log('arr2',arr2)//[1,2,3,4,5,9,0]
sort(原数组和新数组都改变,且按照字符编码,第一个数字排序)
var arr = [1,20,30,104,105]
var arr1 = arr.sort()
console.log('arr',arr) // [1, 104, 105, 20, 30]
console.log('arr1',arr1)//[1, 104, 105, 20, 30]
reverse(原数组和新数组都改变)
var arr = [1,20,30,104,105]
var arr1 = arr.reverse()
console.log('arr',arr) // [105, 104, 30, 20, 1]
console.log('arr1',arr1) // [105, 104, 30, 20, 1]
slice(start,end) (原数组不变,返回截取出来的数组)
(删除从下标start到end的元素)
var arr = [1,2,3,4,5]
var arr1 = arr.slice(2,3)
console.log('arr',arr)// [1,2,3,4,5]
console.log('arr1',arr1)//[3]
map(原数组不变,新数组为计算后的数组)
var arr = [1,2,3,4,5]
var arr1 = arr.map(a => {
return a+1
}
)
console.log('arr',arr) //[1,2,3,4,5]
console.log('arr1',arr1)//[2,3,4,5,6]
filter(原数组不变,新数组为计算后的数组)
var arr = [1,2,3,4,5]
var arr1 = arr.filter(a => {
return a>2
})
console.log('arr',arr) //[1,2,3,4,5]
console.log('arr1',arr1) //[3,4,5]
forEach(原数组不变,没有返回值)
var arr = [1,2,3,4,5]
var arr1 = arr.forEach((a,i) => {
a = 0
})
console.log('arr',arr) //[1,2,3,4,5]
console.log('arr1',arr1) //undefined
forEach(item, index, arr),三个参数,如果直接用item=xxx是无法改变原数组的,但是如果用arr[index]就可以改变原数组。
var s = [1,2,3,4];
s.forEach(item=>{
item = 'a'
});
console.log(s);// ["1", "2", "3", "4"] 未改变原数组
s.forEach((item, index, arr)=>{
arr[index] = 'b'
});
console.log(s);// ["b", "b", "b", "b"] 改变了原数组
数组里面的子元素是对象,那么是可以改变对应属性的
var s = [{a:1}, {a:1}];
s.forEach(item=>{
item = null;
});
console.log(s);//[{a: 1} ,{a: 1}] 未改变原数组
s.forEach(item=>{
item.a = 666;
});
console.log(s); // [{a: 666}, {a: 666}] //改变的原数组里面的对象属性