数组
是值的有序集合,其中值叫做元素,每个元素有一个数值表示的位置,叫做索引*
Js数组是无类型限制.即数组中的元素可以是任何类型,同一个数组的不同元素可以是不同的类型.
JS数组是动态变化的因此创建时无需声明一个固定大小,也无需在大小变化时重新为他们分配空间,JS 数组可以是稀疏的也可以是连续的
JS 数组是一种特殊的 JS 对象,因此数组索引更想属性名,只不过碰巧是整数
数组从 Array.prototype 继承属性
创建数组:
- 数组字面量
- 可迭代对象使用…
- Array()构造函数
- 工厂方法 Array.of()
- 工厂方法: Array.from()
ES5中定义了9个新数组方法来遍历、映射、过滤、检测、简化和搜索数组. *
在大多数情况下,调用提供的函数使用三个参数:
数组元素、元素的索引和数组本身。
通常,只需要第一个参数值,可以忽略后两个参数。
大多数ECMAScript 5数组方法的第一个参数是一个函数
第二个参数是可选的。如果有第二个参数,则调用的函数被看做是第二个参数的方法。
也就是说,在调用函数时传递进去的第二个参数作为它的this关键字的值来使用。被调用的函数的返回值非常重要,但是不同的方法处理返回值的方式也不一样。
ECMAScript 5中的数组方法都不会修改它们调用的原始数组。当然,传递给这些方法的函数是可以修改这些数组的。 —-节选自JavaScript第六版7.9
Array.from()
Array.from()是es6新增的工厂方法.
这个方法期待一个可迭代对象或类数组对象作为其第一个参数,并返回包含该对象元素的新数组,
当传入第二个参数为函数的时候,那么在构建新数组时,源对象的每个元素都会传入这个函数,这个函数的返回值,将替代原始值称为新数组的元素,构建执行映射侠侣高于先构建数组再把它映射成另一个新数组
简单说,可以使用其参数值作为数组元素来创建并返回新数组
Array.from(arrayLike[, mapFn[, thisArg]])
-
arrayLike想要转换成数组的伪数组对象或可迭代对象
-
mapFn可选如果指定了该参数,新数组中的每个元素会执行该回调函数。
-
thisArg可选可选参数,执行回调函数
mapFn时this对象。
Array.from()方法对一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例。
console.log(Array.from('foo'));
// expected output: Array ["f", "o", "o"]
console.log(Array.from([1, 2, 3], x => x + x));
// expected output: Array [2, 4, 6]
filter()
filter()方法返回的数组元素是一个调用的数组子集,filter()会跳过稀疏数组中缺少的元素,它的返回数组总是稠密的
语法:
// Arrow function
filter((element) => { /* ... */ } )
filter((element, index) => { /* ... */ } )
filter((element, index, array) => { /* ... */ } )
// Callback function
filter(callbackFn)
filter(callbackFn, thisArg)
// Inline callback function
filter(function(element) { /* ... */ })
filter(function(element, index) { /* ... */ })
filter(function(element, index, array){ /* ... */ })
filter(function(element, index, array) { /* ... */ }, thisArg)
参数:
callback
为数组中每个元素执行的函数,该函数接收一至三个参数:
-
currentValue数组中正在处理的当前元素。
-
index可选数组中正在处理的当前元素的索引。
-
array可选forEach()方法正在操作的数组。 -
thisArg可选
可选参数。当执行回调函数 callback 时,用作 this 的值。
a = [0,3, 4, 6, 91, 100, 120];
smallvalue = a.filter(function (x) { return x > 100 });
console.log(smallvalue); //[120]
everyother = a.filter(function (x, i) { return i % 2 == 0 })
console.log(everyother); //[ 0, 4, 91, 120 ]
上文提到filter()会跳过稀疏数组缺少的元素,通这个方法我们可以压缩稀疏数组的空缺.删除undefined、null元素,
var dense = sparse.filter(function(){return true});
a= a.filter(function(x){return x!==undefined&&x!==null});
forEach()
forEach() 方法对数组的每个元素执行一次给定的函数。
语法:
// Arrow function
forEach((element) => { /* ... */ } )
forEach((element, index) => { /* ... */ } )
forEach((element, index, array) => { /* ... */ } )
// Callback function
forEach(callbackFn)
forEach(callbackFn, thisArg)
// Inline callback function
forEach(function(element) { /* ... */ })
forEach(function(element, index) { /* ... */ })
forEach(function(element, index, array){ /* ... */ })
forEach(function(element, index, array) { /* ... */ }, thisArg)
示例:
转换for循环为foreach
const items = ['item1', 'item2', 'item3']
const copyItems = []
// before
// for (let i = 0; i < items.length; i++) {
// copyItems.push(items[i])
// }
// after
items.forEach(function (item) {
copyItems.push(item)
})
console.log(items);
console.log(copyItems);
find()
find()方法返回所提供数组中满足所提供测试函数的第一个元素的值。如果没有值满足测试函数,则返回undefined。
示例:
查找素数
function isPrime(element, index, array) {
let start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) {
return false;
}
}
return element > 1;
}
console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found
console.log([4, 5, 8, 12].find(isPrime)); // 5
示例:
// Declare array with no elements at indexes 2, 3, and 4
const array = [0, 1, , , , 5, 6];
// Shows all indexes, not just those with assigned values
array.find(function (value, index) {
console.log('Visited index ', index, ' with value ', value);
});
// Shows all indexes, including deleted
array.find(function (value, index) {
// Delete element 5 on first iteration
if (index === 0) {
console.log('Deleting array[5] with value ', array[5]);
delete array[5];
}
// Element 5 is still visited even though deleted
console.log('Visited index ', index, ' with value ', value);
});
//output
//Visited index 0 with value 0
//Visited index 1 with value 1
//Visited index 2 with value undefined
//Visited index 3 with value undefined
//Visited index 4 with value undefined
//Visited index 5 with value 5
//Visited index 6 with value 6
//Deleting array[5] with value 5
//Visited index 0 with value 0
//Visited index 1 with value 1
//Visited index 2 with value undefined
//Visited index 3 with value undefined
//Visited index 4 with value undefined
//Visited index 5 with value undefined
//Visited index 6 with value 6
使用箭头函数和解构
const inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
const result = inventory.find( ({ name }) => name === 'cherries' );
console.log(result) // { name: 'cherries', quantity: 5 }
findIndex()
findindex()方法:
返回数组中满足提供的测试函数的第一个元素的索引。否则,它返回,表明没有元素通过测试。 -1
示例:
const fruits = ["apple", "banana", "cantaloupe", "blueberries", "grapefruit"];
const index = fruits.findIndex(fruit => fruit === "blueberries");
console.log(index); // 3
console.log(fruits[index]); // blueberries
every()
every()方法测试数组中的所有元素 是否通过提供的函数实现的测试。它返回一个布尔值
语法:
const isBelowThreshold = (currentValue) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13,70];
console.log(array1.every(isBelowThreshold)); //false