-
数组随机打乱
var arr = [47, 16, 35, 90, 81, 10, 59, 84, 61, 13, 94, 74, 43, 87];
randomArr = arr.sort(function(){ return 0.5 - Math.random() })
-
伪数组转成数组
伪数组arrayLike,必须按照索引存储,具有length属性,缺少数组的push,pop等方法
var arrayLike = {
0: "a",
1: "b",
2: "c",
3: "d",
length:4
};
方法一
var arr1 = Array.prototype.slice.call(arrayLike);
方法二
和方法一性质一样且方法一效率更高
var arr2 = [].slice.call(arrayLike);
方法三
ES6中Array.from方法
var arr3 = Array.from(arrayLike);
-
数组内对象排序
var arr = [{aa: 22, zIndex: 2},{aa: 33, zIndex: 3},{aa: 11, zIndex: 1},{aa: 55, zIndex: 5}];
var tem = [];
var arrCopy = [...Array(arr.length).keys()].map((item) => { return item });
arr.forEach((v,i)=>{
tem.push(v.zIndex)
})
tem.sort((v1,v2)=>{ return v1 - v2 });
arr.forEach((value,item)=>{
var nowIndex;
var newValue;
tem.forEach((v,i)=>{
if(value.zIndex === v){
nowIndex = i;
}
});
arrCopy[nowIndex] = value;
});
console.log(arrCopy)
-
数组去重
var arr = [{a:1},1,2,3,1,2,3,{a:1},{a:'1'}];
var newArr = Array.from(new Set(arr.map(item => JSON.stringify(item)))).map(item => JSON.parse(item));
网友评论