Array 对象
·
Yin灏
创建特定数组的副本
复制特定数组实例,可以通过 of() 或 valueOf() 来实现。
let array01 = Array.of(1, 'two', 3, 'four', 5, 'six');
let array02 = [1, 'two', 3, 'four', 5, 'six'];
let array03 = Array(1, 'two', 3, 'four', 5, 'six');
let array04 = new Array(1, 'two', 3, 'four', 5, 'six');
console.log(array01); // [1, "two", 3, "four", 5, "six"]
console.log(array02); // [1, "two", 3, "four", 5, "six"]
console.log(array03); // [1, "two", 3, "four", 5, "six"]
console.log(array04); // [1, "two", 3, "four", 5, "six"]
console.log('');
let array05 = Array.of('January');
let array06 = ['January'];
let array07 = Array('January');
let array08 = new Array('January');
console.log(array05); // ["January"]
console.log(array06); // ["January"]
console.log(array07); // ["January"]
console.log(array08); // ["January"]
console.log('');
let array09 = Array.of(5);
let array10 = [5];
let array11 = Array(5);
let array12 = new Array(5);
console.log(array09); // [5]
console.log(array10); // [5]
console.log(array11); // (5) [empty × 5]
console.log(array12); // (5) [empty × 5]
let a01 = ['1st', '2nd', '3rd', '4th'];
let a02 = ['1st', '2nd', '3rd', '4th'];
// a01 和 a02 内存地址不同
console.log(a01 == a02); // false
let a03 = a01; // 深拷贝
console.log(a01 == a03); // true
console.log('');
// valueOf() 用来取出特定对象实例中的原始数据(深拷贝)
// 经过 valueOf() 处理的实例,和原实例有相同的内存地址
let a04 = a01.valueOf();
console.log(a04); // ["1st", "2nd", "3rd", "4th"]
console.log(a01 == a01.valueOf()); // true
console.log(a01 == a04); // true
创建来自可迭代对象的新数组
要复制其他科迭代对象实例的当前数据,成为新的数组实例的数据,可以通过 Array 对象支持的函数 from() 或 map() 来实现。
let word = 'Happiness';
let a01 = Array.from(word);
console.log(a01); // ["H", "a", "p", "p", "i", "n", "e", "s", "s"]
let a02 = [...word];
console.log(a02); // ["H", "a", "p", "p", "i", "n", "e", "s", "s"]
let a03 = word.split('');
console.log(a03); // ["H", "a", "p", "p", "i", "n", "e", "s", "s"]
let r1 = 12, r2 = 15, r3 = 18;
let circle_area01 = r => (Math.PI * r ** 2).toFixed(2);
let a04 = Array.from([r1, r2, r3], circle_area01);
// r1, r2, r3 三个参数会依次传入 circle_area01() 中,返回的数值组成一个数组
console.log(a04); // ["452.39", "706.86", "1017.88"]
let a05 = Array.from([r1, r2, r3], r => (Math.PI * r ** 2).toFixed(2));
console.log(a05); // ["452.39", "706.86", "1017.88"]
function circle_area02(r) {
return (Math.PI * r ** 2).toFixed(2)
}
let a06 = Array.from([r1, r2, r3], circle_area02);
console.log(a06); // ["452.39", "706.86", "1017.88"]
// 先创建 5 个空元素,然后再依次填入数据
let a07 = Array.from({length: 5}, (value, index) => index ** 3);
console.log(a07); // [0, 1, 8, 27, 64]
let radius_list = [10, 18, 24, 50, 80];
// map() 返回一个新数组
let circle_areas = radius_list.map((r) => (Math.PI * r ** 2).toFixed(2))
console.log(circle_areas); // ["314.16", "1017.88", "1809.56", "7853.98", "20106.19"]
circle_areas = Array.from(radius_list, (r) => (Math.PI * r ** 2).toFixed(2));
console.log(circle_areas); // ["314.16", "1017.88", "1809.56", "7853.98", "20106.19"]
let bases = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100];
let roots = bases.map(Math.sqrt);
console.log(roots); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
roots = bases.map((b) => Math.sqrt(b));
console.log(roots); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
roots = bases.map((b) => b ** 0.5);
console.log(roots); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
数组元素数据所构成的字符串
let fruits = ['apricot', 'blueberry', 'cranberry', 'durian'];
let str01 = fruits.toString();
let str02 = fruits.join(',');
let str03 = fruits.join();
console.log(str01); // apricot,blueberry,cranberry,durian
console.log(str02); // apricot,blueberry,cranberry,durian
console.log(str03); // apricot,blueberry,cranberry,durian
数组元素的放入和取出
let balls = ['baseball', 'basketball'];
balls.push('marble');
console.log(balls); // ["baseball", "basketball", "marble"]
let new_length = balls.push('dodgeball', 'fireball', 'Earth');
console.log(new_length); // 6 返回的是数组的长度
console.log(balls); // ["baseball", "basketball", "marble", "dodgeball", "fireball", "Earth"]
console.log('');
let drawed_data = balls.pop(); // 删除原数组中最后一个元素,并返回这个被删除的元素
console.log(drawed_data); // Earth 返回数组最后一个元素
console.log(balls); // ["baseball", "basketball", "marble", "dodgeball", "fireball"]
drawed_data = balls.shift(); // 删除原数组的第一个元素,并返回该元素
console.log(drawed_data); // baseball
console.log(balls); // ["basketball", "marble", "dodgeball", "fireball"]
balls.unshift('Pluto'); // 从数组前面开始添加元素
console.log(balls); // ["Pluto", "basketball", "marble", "dodgeball", "fireball"]
balls.unshift('Moon', 'Mars');
console.log(balls); // ["Moon", "Mars", "Pluto", "basketball", "marble", "dodgeball", "fireball"]
新增和删除数组的多个元素
let vegetables = ['Lettuce', 'broccoli', 'spinach', 'kale', 'cabbage', 'onion', 'greenbeans'];
console.log(vegetables);
// 数组截取
// 从索引 1 开始,一共截取两个元素,并在原数组中去掉这两个元素
let drawed_list = vegetables.splice(1, 2);
console.log(drawed_list); // ['broccoli', 'spinach']
console.log(vegetables); // ["Lettuce", "kale", "cabbage", "onion", "greenbeans"]
// 给数组添加元素
vegetables.splice(1, 0, ...drawed_list);
console.log(vegetables); // ["Lettuce", "broccoli", "spinach", "kale", "cabbage", "onion", "greenbeans"]
vegetables.splice(3, 0, 'garlic');
console.log(vegetables); // ["Lettuce", "broccoli", "spinach", "garlic", "kale", "cabbage", "onion", "greenbeans"]
合并多个数组
let a01 = [1, 3, 5];
let a02 = [2, 4, 6];
let a03 = ['x', 'y', 'z'];
let combination = a01.concat(a02, a03);
console.log(combination); // [1, 3, 5, 2, 4, 6, "x", "y", "z"]
combination = [...a01, ...a02, ...a03];
console.log(combination); // [1, 3, 5, 2, 4, 6, "x", "y", "z"]
切割数组
let vegetables = ['Lerruce', 'broccoli', 'spinach', 'kale', 'cabbage', 'onion', 'green beans'];
let sliced_list = vegetables.slice(2); // 原数组不变
console.log(vegetables); // ["Lerruce", "broccoli", "spinach", "kale", "cabbage", "onion", "green beans"]
console.log(sliced_list); // 截取从索引 2(包含索引2)到数组最后的元素,生成一个新数组
sliced_list = vegetables.slice(3, 6); // [3, 6)
console.log(vegetables); // ["Lerruce", "broccoli", "spinach", "kale", "cabbage", "onion", "green beans"]
console.log(sliced_list); // ["kale", "cabbage", "onion"]
sliced_list = vegetables.slice(-2); // -2 + 7 = 5 从索引 5 开始截取
console.log(vegetables); // ["Lerruce", "broccoli", "spinach", "kale", "cabbage", "onion", "green beans"]
console.log(sliced_list); // ["onion", "green beans"]
寻找符合特定条件的数组元素
let numbers = [10, 30, 20, 55, 15, 70, 23];
numbers.sort(); // 首字母排序
console.log(numbers); // [10, 15, 20, 23, 30, 55, 70]
let gt3 = n => n > 30;
console.log(numbers.find(gt3)); // 55
console.log(numbers.findIndex(gt3)); // 5
自我复制并覆盖数组的部分元素
let a00 = ['a', 'b', 'c', 'd', 'e', 'f'];
let a01 = ['a', 'b', 'c', 'd', 'e', 'f'];
let a02 = ['a', 'b', 'c', 'd', 'e', 'f'];
let a03 = ['a', 'b', 'c', 'd', 'e', 'f'];
let a04 = ['a', 'b', 'c', 'd', 'e', 'f'];
a01.copyWithin(2); // 获取数组自身元素,并从索引 2 开始覆盖
console.log(a01); // ["a", "b", "a", "b", "c", "d"]
a02.copyWithin(-2); // 从索引为 -2 的,倒数第二个元素开始覆盖
console.log(a02); // ["a", "b", "c", "d", "a", "b"]
a03.copyWithin(0, 2); // 从索引为 0 开始,被连续覆盖(从索引值 2 的元素开始)的连续元素
console.log(a03); // ["c", "d", "e", "f", "e", "f"]
// 从索引值为 -3(倒数第3个)的元素 ‘d’ 开始,被连续覆盖【从索引值1(第2个)的元素 'b' 开始,到索引值为 3 - 1 = 2(第 3 个)的元素 'c' 开始】的两个元素
a04.copyWithin(-3, 1, 3);
console.log(a04); // ["a", "b", "c", "b", "c", "f"]
判断数组各元素是否符合特定条件
function comparing(value, index, array) {
return value > 0 && value < 20;
}
let a01 = [24, 36, 10, 5, -2];
let a02 = [1, 15, 8, 3, 19];
console.log(a01.every(comparing)); // false
console.log(a02.every(comparing)); // true
console.log(a01.some(comparing)); // true
console.log(a02.some(comparing)); // true
数组部分元素的填充
let template = ['a', 'b', 'c', 'd', 'e', 'f'];
let a01 = template.slice(0);
console.log(template); // ["a", "b", "c", "d", "e", "f"]
console.log(a01); // ["a", "b", "c", "d", "e", "f"]
a01.fill('?')
console.log(a01); // ["?", "?", "?", "?", "?", "?"]
a01 = template.slice(0);
console.log(a01); // ["a", "b", "c", "d", "e", "f"]
a01.fill('$', 2); // 从索引 2 向后填充
console.log(a01); // ["a", "b", "$", "$", "$", "$"]
a01 = template.slice(0);
a01.fill('*', 2, 5); // 从 索引 2 填充到索引 5 [2, 5)
console.log(a01); // ["a", "b", "*", "*", "*", "f"]
a01 = template.slice(0);
a01.fill('^', 1, -2); //
console.log(a01); // ['a', '^', '^', '^', 'e', 'f']
a01 = Array(7).fill('@_@');
console.log(a01); // ["@_@", "@_@", "@_@", "@_@", "@_@", "@_@", "@_@"]
筛选出符合特定条件的数组元素
let names = ['Eric', 'Sam', 'Jimy', 'Paula', 'Daisy', 'Jennifer', 'Sean'];
function check(name) {
return name.length < 5;
}
let shorts = names.filter(check);
console.log(shorts); // ["Eric", "Sam", "Jimy", "Sean"]
let numbers = [123, 456, 789, 55, 22, 33];
let smalls = numbers.filter(num => num % 3 == 0);
console.log(smalls); // [123, 456, 789, 33]
循环访问数组各元素
let shapes = ['circle', 'triangle', 'rectangle', 'trapezoid', 'pentagons', 'hexagon', 'heptagon', 'octagon', 'star'];
function display(value) {
console.log(value);
}
shapes.forEach(display);
console.log('');
shapes.forEach(value => console.log(value));
判断是否为数组的实例
let instance;
with(console) {
instance = [];
log(Array.isArray(instance)) // true
instance = Array(3);
log(Array.isArray(instance)) // true
instance = new Array(3);
log(Array.isArray(instance)) // true
instance = {};
log(Array.isArray(instance)) // false
instance = parseInt(100 * Math.random())
log(Array.isArray(instance)); // false
instance = instance < 50;
console.log(Array.isArray(instance)); // false
}
访问并渐次处理数组各元素的数据
let numbers = [2, 3, 7, 11, 13, 17, 19, 23, 29];
let totals = numbers.reduce((pile, current) => pile + current);
console.log(totals); // 124
totals = numbers.reduce((pile, current) => pile + current, 0);
console.log(totals); // 124
totals = numbers.reduce((pile, current) => pile + current, 200);
console.log(totals); // 324
let n01 = [3, 7, 2, 9];
let n02 = [10, 80, 50, 70];
let n03 = [200, 500, 100, 400];
let matrix = [n01, n02, n03];
function vertically_add(piles, current) {
for(let i = 0; i < piles.length; i++) {
piles[i] += current[i];
}
return piles;
}
let column_summations = matrix.reduce(vertically_add, Array(n01.length).fill(0));
console.log(column_summations); // [213, 587, 152, 479]
let box = ['apple', 'guava', 'durian', 'apple', 'guava', 'peach', 'apricot', 'peach', 'durian', 'apple'];
function count_fruit (piles, current) {
if(!(current in piles)) {
piles[current] = 1;
} else {
piles[current]++;
}
return piles;
}
let inventory = box.reduce(count_fruit, {});
console.log(inventory); // {apple: 3, guava: 2, durian: 2, peach: 2, apricot: 1}
let numbers = [2, 3, 7, 11, 13, 17, 19, 23, 29];
let message = '';
function summation(pile, current) {
message += ' ->' + current;
return pile + current;
}
totals = numbers.reduce(summation, 0)
console.log(message); // ->2 ->3 ->7 ->11 ->13 ->17 ->19 ->23 ->29
console.log(totals); // 124
message = '';
// 从右向左处理数据
totals = numbers.reduceRight(summation, 0);
console.log(message); // ->29 ->23 ->19 ->17 ->13 ->11 ->7 ->3 ->2
console.log(totals); // 124
反转数组各元素的顺序
let flowers = ['lily', 'jasmine', 'rose', 'daisy', 'daffodil', 'camellia'];
flowers.reverse();
console.log(flowers); // ["camellia", "daffodil", "daisy", "rose", "jasmine", "lily"]
数组各元素的重新排序
let a01 = Array.from({length: 7}, () => parseInt(100 * Math.random()));
console.log(a01); // [19, 74, 69, 68, 13, 68, 91]
let a02 = a01.sort();
console.log(a02); // [13, 19, 68, 68, 69, 74, 91]
function set_descending(previos, current) {
return current - previos;
}
let a03 = a01.sort(set_descending);
console.log(a03); // [91, 74, 69, 68, 68, 19, 13]
判断特定元素的存在性
let int_list = [1, 10, 18, 23, 29, 37, 56];
let str_list = ['keyboard', 'mouse', 'screen', 'speaker'];
let result;
result = int_list.indexOf(23);
console.log(result); // 3
result = int_list.includes(23);
console.log(result); // true
result = int_list.indexOf(45);
console.log(result); // -1
result = int_list.includes(45);
console.log(result); // false
result = str_list.indexOf('speaker');
console.log(result); // 3
result = str_list.includes('speaker');
console.log(result); // true