javascript 中 数组常用的方法

2019-06-18  本文已影响0人  _一九九一_

本文参考MDN

Array.prototype.some()

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()

// 返回现有数组的一部分
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()

const array1 = [{a:1}];
array1.forEach(element => element.a=2);
const array1 = [1];
array1.forEach(element => element+1);
上一篇 下一篇

猜你喜欢

热点阅读