11、forEach() 的使用
forEach() 方法对数组的每个元素执行一次提供的函数。
语法:arr.forEach(callback[, thisArg])
参数:
|---callback:为数组中每个元素执行的函数,该函数接收三个参数:
|--- currentValue: 数组中正在处理的当前元素;
|--- index: 可选,数组中正在处理的当前元素的索引;
|--- array: 可选,forEach() 方法正在操作的数组;
|---thisArg:可选参数。当执行回调函数时用作 this 的值(参考对象);返回值:
|--- undefined
注意: 没有办法中止或者跳出
forEach()
循环,除了抛出一个异常。如果你需要这样,使用forEach()
方法是错误的。若你需要提前终止循环,你可以使用:
- 简单循环
for...of
循环Array.prototype.every()
Array.prototype.some()
Array.prototype.find()
Array.prototype.findIndex()
这些数组方法可以对数组元素判断,以便确定是否需要继续遍历:
every()
,some()
,find()
,findIndex()
注:若条件允许,也可以使用
filter()
提前过滤出需要遍历的部分,再用forEach()
处理。
实例1:for 循环转换为 forEach
const items = ['item1', 'item2', 'item3'];
const copy1 = [];
const copy2 = [];
// before
for (let i=0; i<items.length; i++) {
copy1.push(items[i]);
}
console.log(copy1); //["item1", "item2", "item3"]
// after
items.forEach(function(item){
copy2.push(item);
});
console.log(copy2); //["item1", "item2", "item3"]
12、from() 的使用
从一个类似数组或可迭代的对象中创建一个新的、浅拷贝的数组实例;
语法:arr.forEach(callback[, thisArg])
参数:
|--- arrayLike:想要转换成数组的伪数组对象或可迭代对象;
|--- mapFn:可选参数。如果指定了该参数,新数组中的每个元素会执行该回调函数;
|--- thisArg:可选参数。可选参数,执行回调函数 mapFn 时 this 对象;返回值:
|--- 一个新的数组实例;
实例1:Array from a String
console.log(Array.from('foo')); //["f", "o", "o"]
实例2:Array from a Set
let s = new Set(['foo', window]);
console.log(Array.from(s)); // ["foo", window]
实例3:Array from a Map
let m = new Map([[1, 2], [2, 4], [4, 8]]);
console.log(Array.from(m));
/*
(3) [array(2), array(2), array(2)]
0: (2) [1, 2]
1: (2) [2, 4]
2: (2) [4, 8]
length: 3
__proto__: array(0)
*/
实例4:在Array.from中使用箭头函数
// Using an arrow function as the map function to
// manipulate the elements
console.log(Array.from([1, 2, 3], x => x + x)); // [2, 4, 6]
// x => x + x代表这是一个函数,只是省略了其他的定义,这是一种Lambda表达式的写法
// 箭头的意思表示从当前数组中取出一个值,然后自加,并将返回的结果添加到新数组中
// Generate a sequence of numbers
// Since the array is initialized with `undefined` on each position,
// the value of `v` below will be `undefined`
console.log(Array.from({length: 5}, (v, i) => i)); // [0, 1, 2, 3, 4]
实例5:数组去重合并
function combine(){
let arr = [].concat.apply([], arguments); //没有去重复的新数组
console.log(arr); //[1, 2, 2, 2, 3, 3]
return Array.from(new Set(arr));
}
var m = [1, 2, 2], n = [2,3,3];
console.log(combine(m,n)); //[1, 2, 3]
13、includes() 的使用
includes() 方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回false。
注意:对象数组不能使用includes方法来检测。
语法:arr.includes(valueToFind[, fromIndex])
参数:
|--- valueToFind:需要查找的元素值;
|--- fromIndex:可选参数。从fromIndex 索引处开始查找 valueToFind。如果为负值,则按升序从 array.length + fromIndex 的索引开始搜 (即,从末尾开始往前跳 fromIndex 的绝对值个索引,然后往后搜寻)。默认为 0;返回值:
|--- 返回一个布尔值Boolean
,如果在数组中找到了(如果传入了fromIndex
,表示在fromIndex
指定的索引范围中找到了)则返回true
。注意: 使用 includes()比较字符串和字符时是区分大小写。
实例1:
console.log([1, 2, 3].includes(2)); // true
console.log([1, 2, 3].includes(4)); // false
console.log([1, 2, 3].includes(3, 3)); // false
console.log([1, 2, 3].includes(3, -1)); // true
console.log([1, 2, NaN].includes(NaN)); // true
实例2:fromIndex 大于等于数组长度
//如果 fromIndex 大于等于数组的长度,则会返回 false,且该数组不会被搜索
var arr = ['a', 'b', 'c'];
console.log(arr.includes('c', 3)); // false
console.log(arr.includes('c', 100)); // false
实例3:计算出的索引小于0
//如果 fromIndex 为负值,计算出的索引将作为开始搜索searchElement的位置。
//如果计算出的索引小于 0,则整个数组都会被搜索。
var arr = ['a', 'b', 'c'];
console.log(arr.includes('a', -100)); // true
console.log(arr.includes('b', -100)); // true
console.log(arr.includes('c', -100)); // true
console.log(arr.includes('a', -2)); // false
实例4:作为通用方法的 includes()
/*
includes() 方法有意设计为通用方法。
它不要求this值是数组对象,所以它可以被用于其他类型的对象 (比如类数组对象)。
下面的例子展示了 在函数的 arguments 对象上调用的 includes() 方法。
*/
(function() {
console.log([].includes.call(arguments, 'a')); // true
console.log([].includes.call(arguments, 'd')); // false
})('a','b','c');
14、indexOf() 的使用
indexOf()方法返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1。
语法:arr.indexOf(searchElement)
arr.indexOf(searchElement[, fromIndex = 0])参数:
|--- searchElement:要查找的元素;
|--- fromIndex:开始查找的位置。如果该索引值大于或等于数组长度,意味着不会在数组里查找,返回-1。如果参数中提供的索引值是一个负值,则将其作为数组末尾的一个抵消,即-1表示从最后一个元素开始查找,-2表示从倒数第二个元素开始查找 ,以此类推。 注意:如果参数中提供的索引值是一个负值,并不改变其查找顺序,查找顺序仍然是从前向后查询数组。如果抵消后的索引值仍小于0,则整个数组都将会被查询。其默认值为0。返回值:
|--- 首个被找到的元素在数组中的索引位置; 若没有找到则返回 -1 。
实例1:
//使用indexOf方法确定多个值在数组中的位置
var array = [2, 5, 9];
console.log(array.indexOf(2)); // 0
console.log(array.indexOf(7)); // -1
console.log(array.indexOf(9, 2)); // 2
console.log(array.indexOf(2, -1)); // -1
console.log(array.indexOf(2, -3)); // 0
实例2:找出指定元素出现的所有位置
var indices = [];
var array = ['a', 'b', 'a', 'c', 'a', 'd'];
var element = 'a';
var idx = array.indexOf(element);
while (idx != -1) {
indices.push(idx);
idx = array.indexOf(element, idx + 1);
}
console.log(indices); // [0, 2, 4]
实例3:判断一个元素是否在数组里,不在则更新数组
function updateVegetablesCollection (veggies, veggie) {
if (veggies.indexOf(veggie) === -1) {
veggies.push(veggie);
console.log('新的 veggies 集合是 : ' + veggies);
//新的 veggies 集合是 : potato,tomato,chillies,green-pepper,spinach
} else if (veggies.indexOf(veggie) > -1) {
console.log(veggie + '已经存在在 veggies 集合中。');
//spinach已经存在在 veggies 集合中。
}
}
var veggies = ['potato', 'tomato', 'chillies', 'green-pepper'];
updateVegetablesCollection(veggies, 'spinach');
console.log(veggies); //["potato", "tomato", "chillies", "green-pepper", "spinach"]
updateVegetablesCollection(veggies, 'spinach');
console.log(veggies);//["potato", "tomato", "chillies", "green-pepper", "spinach"]
15、isArray() 的使用
Array.isArray() 用于确定传递的值是否是一个 Array。
语法:Array.isArray(obj)
参数:
|--- obj:需要检测的值;返回值:
|--- 如果对象是Array
,则为true; 否则为false 。
实例1:
// 下面的函数调用都返回 true
Array.isArray([]);
Array.isArray([1]);
Array.isArray(new Array());
// 鲜为人知的事实:其实 Array.prototype 也是一个数组。
Array.isArray(Array.prototype);
// 下面的函数调用都返回 false
Array.isArray();
Array.isArray({});
Array.isArray(null);
Array.isArray(undefined);
Array.isArray(17);
Array.isArray('Array');
Array.isArray(true);
Array.isArray(false);
Array.isArray({ __proto__: Array.prototype });
实例2:instanceof 和 isArray
// 当检测Array实例时, Array.isArray 优于 instanceof,因为Array.isArray能检测iframes.
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
xArray = window.frames[window.frames.length-1].Array;
var arr = new xArray(1,2,3); // [1,2,3]
// Correctly checking for Array
console.log(Array.isArray(arr));; // true
// Considered harmful, because doesn't work though iframes
console.log(arr instanceof Array);; // false
16、join() 的使用
join() 方法将一个数组(或类数组)对象的所有元素连接成一个字符串并返回这个字符串。如果数组只有一个项目,那么将返回该项目而不使用分隔符。
语法:arr.join([separator])
参数:
|--- separator:指定一个字符串来分隔数组的每个元素。如果需要,将分隔符转换为字符串。如果省略(),数组元素用逗号分隔。默认为 ","。如果separator是空字符串(""),则所有元素之间都没有任何字符;返回值:
|--- 一个所有数组元素连接的字符串。如果 arr.length 为0,则返回空字符串。注:如果一个元素为 undefined 或 null,它会被转换为空字符串。
实例1:使用四种不同的分隔符连接数组元素
var a = ['Wind', 'Rain', 'Fire'];
var myVar1 = a.join(); // myVar1的值变为"Wind,Rain,Fire"
console.log(myVar1); //Wind,Rain,Fire
var myVar2 = a.join(', '); // myVar2的值变为"Wind, Rain, Fire"
console.log(myVar2); //Wind,Rain,Fire
var myVar3 = a.join(' + '); // myVar3的值变为"Wind + Rain + Fire"
console.log(myVar3); //Wind + Rain + Fire
var myVar4 = a.join(''); // myVar4的值变为"WindRainFire"
console.log(myVar4); //WindRainFire
实例2:连接类数组对象
/*
* 连接类数组对象(arguments),通过在Array.prototype.join上调用Function.prototype.call。
**/
function f(a, b, c) {
var s = Array.prototype.join.call(arguments);
console.log(s); // '1,a,true'
}
f(1, 'a', true);
17、keys() 的使用
keys() 方法返回一个包含数组中每个索引键的Array Iterator对象。
语法:arr.keys()
返回值:
|--- 一个新的 Array 迭代器对象。
实例1:索引迭代器会包含那些没有对应元素的索引
var arr = ["a", , "c"];
var sparseKeys = Object.keys(arr);
var denseKeys = [...arr.keys()];
console.log(sparseKeys); // ['0', '2']
console.log(denseKeys); // [0, 1, 2]
18、lastIndexOf() 的使用
lastIndexOf() 方法返回指定元素(也即有效的 JavaScript 值或变量)在数组中的最后一个的索引,如果不存在则返回 -1。从数组的后面向前查找,从 fromIndex 处开始。
语法:arr.lastIndexOf(searchElement[, fromIndex = arr.length - 1])
参数:
|--- searchElement:被查找的元素
|--- fromIndex:从此位置开始逆向查找。默认为数组的长度减 1,即整个数组都被查找。如果该值大于或等于数组的长度,则整个数组会被查找。如果为负值,将其视为从数组末尾向前的偏移。即使该值为负,数组仍然会被从后向前查找。如果该值为负时,其绝对值大于数组长度,则方法返回 -1,即数组不会被查找。返回值:
|--- 数组中最后一个元素的索引,如未找到返回-1。
实例1:使用 lastIndexOf
var array = [2, 5, 9, 2];
var index = array.lastIndexOf(2);
console.log(index); //3
index = array.lastIndexOf(7);
console.log(index); //-1
index = array.lastIndexOf(2, 3);
console.log(index); //3
index = array.lastIndexOf(2, 2);
console.log(index); //0
index = array.lastIndexOf(2, -2);
console.log(index); //0
index = array.lastIndexOf(2, -1);
console.log(index); //3
实例2:查找所有元素
/*
lastIndexOf 查找到一个元素在数组中所有的索引(下标),
并使用 push 将所有添加到另一个数组中。
*/
var indices = [];
var array = ['a', 'b', 'a', 'c', 'a', 'd'];
var element = 'a';
var idx = array.lastIndexOf(element);
while (idx != -1) {
indices.push(idx);
idx = (idx > 0 ? array.lastIndexOf(element, idx - 1) : -1);
}
console.log(indices); // [4, 2, 0];
/*
注意,要单独处理idx==0时的情况,因为如果是第一个元素,
忽略了fromIndex参数则第一个元素总会被查找。这不同于indexOf方法
idx = (idx > 0 ? array.lastIndexOf(element, idx - 1) : -1);
idx > 0时,才进入lastIndexOf由后往前移一位进行倒查找;如果idx == 0则直接设置idx = -1,
循环while (idx != -1)就结束了
*/
19、map() 的使用
map() 通过指定函数处理数组中的每个元素,返回处理后的数组。
语法:var new_array = arr.map(function callback(currentValue[, index[, array]]) {
// Return element for new_array
}[, thisArg])参数:
|--- callback:生成新数组元素的函数,使用三个参数:
|--- currentValue:callback 数组中正在处理的当前元素;
|--- index: 可选, 数组中正在处理的当前元素的索引;
|--- array: 可选,map 方法被调用的数组;
|--- thisArg:执行 callback 函数时使用的this 值;返回值:
|--- 一个新数组,每个元素都是回调函数的结果。
实例1:求数组中每个元素的平方根
var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
console.log(roots); //[1, 2, 3]
// roots的值为[1, 2, 3], numbers的值仍为[1, 4, 9]
实例2:使用 map 重新格式化数组中的对象
//用一个包含对象的数组来重新创建一个格式化后的数组
var kvArray = [{key: 1, value: 10},
{key: 2, value: 20},
{key: 3, value: 30}];
var reformattedArray = kvArray.map(function(obj) {
var rObj = {};
rObj[obj.key] = obj.value;
return rObj;
});
console.log(reformattedArray);
// reformattedArray 数组为: [{1: 10}, {2: 20}, {3: 30}],
// kvArray 数组未被修改:
// [{key: 1, value: 10},
// {key: 2, value: 20},
// {key: 3, value: 30}]
实例3:使用一个包含一个参数的函数来mapping(构建)一个数字数组
var numbers = [1, 4, 9];
var doubles = numbers.map(function(num) {
return num * 2;
});
console.log(doubles);
// doubles数组的值为: [2, 8, 18]
// numbers数组未被修改: [1, 4, 9]
实例4:一般的map 方法
var map = Array.prototype.map
var a = map.call("Hello World", function(x) {
return x.charCodeAt(0);
})
// a的值为[72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
实例5:使用技巧案例
通常情况下,map 方法中的 callback 函数只需要接受一个参数,就是正在被遍历的数组元素本身。但这并不意味着 map 只给 callback 传了一个参数。这个思维惯性可能会让我们犯一个很容易犯的错误。
// 下面的语句返回什么呢:
["1", "2", "3"].map(parseInt);
// 你可能觉的会是[1, 2, 3]
// 但实际的结果是 [1, NaN, NaN]
// 通常使用parseInt时,只需要传递一个参数.
// 但实际上,parseInt可以有两个参数.第二个参数是进制数.
// 可以通过语句"alert(parseInt.length)===2"来验证.
// map方法在调用callback函数时,会给它传递三个参数:当前正在遍历的元素,
// 元素索引, 原数组本身.
// 第三个参数parseInt会忽视, 但第二个参数不会,也就是说,
// parseInt把传过来的索引值当成进制数来使用.从而返回了NaN.
function returnInt(element) {
return parseInt(element, 10);
}
['1', '2', '3'].map(returnInt); // [1, 2, 3]
// 意料之中的结果
// 也可以使用简单的箭头函数,结果同上
['1', '2', '3'].map( str => parseInt(str) );
// 一个更简单的方式:
['1', '2', '3'].map(Number); // [1, 2, 3]
// 与`parseInt` 不同,下面的结果会返回浮点数或指数:
['1.1', '2.2e2', '3e300'].map(Number); // [1.1, 220, 3e+300]
20、pop() 的使用
pop()方法从数组中删除最后一个元素,并返回该元素的值。此方法更改数组的长度。
语法:arr.pop()
返回值:
|--- 从数组中删除的元素(当数组为空时返回 undefined)。
实例1:删除掉数组的最后一个元素
let myFish = ["angel", "clown", "mandarin", "surgeon"];
let popped = myFish.pop();
console.log(myFish); // ["angel", "clown", "mandarin"]
console.log(popped); // surgeon
后文,继续......
网友评论