let arr = {
0: "1",
1: "2",
length: 3
};
// 将伪数组或可遍历对象变为真正的数组
let arr2 = Array.from(arr);
console.log(arr2); // [ '1', '2', undefined ]
// 将数组的每个元素进行运算
let newArr = Array.from(arr, item => {
return item * 2;
});
console.log(newArr); // [ 2, 4, NaN ]
let arr = [
{ index: 1, name: "jack" },
{ index: 2, name: "tom" }
];
// 查找对象
let target = arr.find((item, index) => {
return item.index === 2;
});
console.log(target); // {index: 2, name: "tom"}
let arr = [1, 5, 12, 66, 99];
// 查找数组成员位置 (大于70的数组元素位置),没有返回为-1
let index = arr.findIndex((value, index) => {
return value > 70;
});
console.log(index); // 4
// 是否包含给定的值
console.log(arr.includes(12)); // true
// 合并数组
let array1 = [1, 2, 3];
let array2 = [4, 5, 6];
array1.push.apply(array1, array2)
console.log(array1); // [1,2,3,4,5,6];
// 把NodeList转换成数组
let elements = document.querySelectorAll("p"); // NodeList
let arrayElements = [].slice.call(elements); // 现在已经转换成数组了
arrayElements = Array.from(elements); // 把NodeList转换成数组的另外一个方法
// 打乱数组
let list = [1, 2, 3];
console.log(list.sort(function() {
return Math.random() - 0.5
})); // [2,1,3]
// 根据一个已有数组创建一个新数组(属于浅拷贝一个新数组)
let array1 = [1, 2, 3, 4, 5, 6]
let array2 = Array.from(array1)
console.log(array2) // [ 1, 2, 3, 4, 5, 6 ]
// 根据传入的参数创建一个新数组
let array3 = Array.of(...array1)
console.log(array3) // [ 1, 2, 3, 4, 5, 6 ]
// 静态值填充数组
let array4 = Array.of(...array1)
// 从数组位置3起到5,所有的值都是1
array4.fill(1, 3, 5)
console.log(array4) // [ 1, 2, 3, 1, 1, 6 ]
// 从数组位置1起,所有的值都是2
array4.fill(2, 1)
console.log(array4) // [ 1, 2, 2, 2, 2, 2 ]
// 全部填充为0
array4.fill(0)
console.log(array4) // [ 0, 0, 0, 0, 0, 0 ]
// 自定义排序
let data = [
{name: 'jack', age: 19},
{name: 'tom', age: 39},
{name: 'tony', age: 29},
]
function desc(x, y) {
return (x['age'] < y['age']) ? 1 : -1
}
function asc(x, y) {
return (x['age'] > y['age']) ? 1 : -1
}
console.log(data.sort(desc))
console.log(data.sort(asc))