1、改变原数组
push、pop、shift、unshift、sort、reverse、splice
2、不可改变原数组
concat、join、split、toString、slice
var obj = {
}
obj.fun = function(){
console.log(1)
}
//这个是函数表达式
splice(从第几位开始,截取多少的长度,在切口处添加新数据)
var arr = [1,2,3,4,5,6]
arr.splice(1,4,0,0,0,0,0)
console.log(arr) //[1, 0, 0, 0, 0, 6]
var arr = [1,2,3,4,5,6]
arr.splice(1,0,0,0,0,0)
console.log(arr) //[1, 0, 0, 0, 0, 2, 3, 4, 5, 6] 第二个参数为0不切数组,在切口处插入
sort() 排序
//升序
var arr = [4,5,6,4,3,4,5,6,7,9,9]
arr.sort()
console.log(arr) //[3, 4, 4, 4, 5, 5, 6, 6, 7, 9, 9]
//降序
var arr = [4,5,6,4,3,4,5,6,7,9,9]
arr.sort().reverse()
console.log(arr) //[9, 9, 7, 6, 6, 5, 5, 4, 4, 4, 3]
var arr = [4,5,6,4,3,4,5,6,7,9,9]
// 1、必须写两形参
// 2、为正数,那么后面的数在前
// 3、为0,不动
arr.sort((a,b)=>{
return a - b //升序 b - a降序
})
console.log(arr) //[3, 4, 4, 4, 5, 5, 6, 6, 7, 9, 9]
//产生随机数
var arr = [4,5,6,4,3,4,5,6,7,9,9]
// 1、必须写两形参
// 2、为正数,那么后面的数在前
// 3、为0,不动
arr.sort(()=>{
return Math.random()-0.5
})
console.log(arr) //每次结果不确定
//对象排序
var obj1 = {
age:12
}
var obj2 = {
age:14
}
var obj3 = {
age:10
}
var arr = [obj1,obj2,obj3];
arr.sort((a,b)=>{
return a.age - b.age
})
console.log(arr) //升序
//按照字符串长度排序
var arr = ['sdfs','sdfsfdfdsfdsfds','sdf','dfgdfg']
arr.sort((a,b)=>{
return b.length - a.length
})
console.log(arr) //["sdfsfdfdsfdsfds", "dfgdfg", "sdfs", "sdf"]
join()
var arr = [1,2,3,4,5]
console.log(arr.join(' ')) //1-2-3-4-5
split()
var arr = [1,2,3,4,5];
var str = arr.join('-');
console.log(str) //1-2-3-4-5
console.log(str.split('-')) //["1", "2", "3", "4", "5"]
数组去重
var arr = [1,1,1,1,5,5,5,4,5,6,7,8,9,2]
Array.prototype.unique = function(){
var temp = [],
arr = [],
len = this.length;
for(var i = 0; i < len; i ++){
if(!temp[this[i]]){
temp[this[i]] = 'a';
arr.push(this[i])
}
}
return arr;
}
//[1, 5, 4, 6, 7, 8, 9, 2]
3、some()方法
var arr = [1,2,3,4,5];
var arr1 = arr.some((item,index,arr)=>{
console.log(item,index,arr)
return item >=5
})
console.log(arr1) //true
网友评论