Array.prototype.some()
- 测试数组中是不是
至少有1个元素
通过了被提供的函数测试。它返回的是一个Boolean类型的值。 - 如果用一个空数组进行测试,在任何情况下它返回的都是false。
const array = [1, 2, 3, 4, 5];
// checks whether an element is even
const even = (element) => element % 2 === 0;
console.log(array.some(even));
// expected output: true
Array.prototype.every()
- 测试一个数组内的
所有元素
是否都能通过某个指定函数的测试。它返回一个布尔值。
const isBelowThreshold = (currentValue) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));
// expected output: true
Array.prototype.unshift()
- 将一个或多个元素添加到数组的开头,并返回该数组的新长度(该方法修改原有数组)。
const array1 = [1, 2, 3];
console.log(array1.unshift(4, 5));
// expected output: 5
console.log(array1);
// expected output: Array [4, 5, 1, 2, 3]
Array.prototype.shift()
- 从数组中删除第一个元素,并返回被删元素的值。此方法更改数组的长度(该方法修改原有数组)。
const array1 = [1, 2, 3];
const firstElement = array1.shift();
console.log(array1);
// expected output: Array [2, 3]
console.log(firstElement);
// expected output: 1
Array.prototype.push()
- 将一个或多个元素添加到数组的末尾,并返回该数组的新长度。(该方法修改原有数组)。
const a = ['1', '2', '3'];
const count = b.push('4');
console.log(count)
// expected output: 4
console.log(a);['1', '2', '3','4'];
animals.push('chickens', 'cats', 'dogs');
console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]
Array.prototype.pop()
- 从数组中删除最后一个元素,并返回该元素的值。此方法更改数组的长度。(该方法修改原有数组)。
const a = ['1', '2', '3', '4', '5'];
console.log(a.pop());
// expected output: '5'
console.log(a);
// expected output: Array ['1', '2', '3', '4'];
a.pop();
console.log(a);
// expected output: Array ['1', '2', '3'];
Array.prototype.splice()
- 通过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回被修改的内容。(此方法会改变原数组)
const a = ['1', '2', '3', '4'];
a.splice(1, 0, 'aaa'); // 在下标1的地方删除0个,插入aaa
// inserts at index 1
console.log(a);
// expected output: Array ["1", "aaa", "2", "3", "4]
a.splice(4, 1, 'bbb'); // 在下标4的地方,删除1个,插入bbb
// replaces 1 element at index 4
console.log(a);
// expected output: Array ["1", "aaa", "2", "3", "bbb"]
Array.prototype.slice()
- 返回一个新的数组对象,这一对象是一个由 begin 和 end 决定的原数组的浅拷贝(包括 begin,不包括end)。(原始数组不会被改变)
// 返回现有数组的一部分
var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
var citrus = fruits.slice(1, 3); // 从下标1的位置开始截取 坐标3的位置结束 不包含3
// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
// citrus contains ['Orange','Lemon']
Array.prototype.forEach()
- 对数组的每个元素执行一次提供的函数。
- forEach() 被调用时,不会改变原数组
但是 callback 函数在被调用时可能会改变原数组
- 引用类型就会改变
const array1 = [{a:1}];
array1.forEach(element => element.a=2);
- 基本类型不会改变原数组
const array1 = [1];
array1.forEach(element => element+1);
网友评论