8.1数组概览

数组是有序的下标从0开始
数组中的元素可以是不同类型
每个数组都有一个length属性

  1. const arr1 = [1, 2, 3]; //整数数组
  2. const arr2 = ["one", 2, "three"]; //非齐次数组
  3. const arr3 = [ //包含数组的非齐次数组
  4. [1, 2, 3],
  5. ["one", 2, "three"]
  6. ];
  7. const arr4 = [{ //非齐次数组
  8. name: "Fred",
  9. type: "object",
  10. luckyNumbers:[5, 7, 13]
  11. },
  12. [{
  13. name: "Susan",
  14. type: "object"
  15. },
  16. {
  17. name: "Anthony",
  18. type: "object"
  19. }
  20. ], 1,
  21. function() {
  22. return "arrays can contain functions too";
  23. }, "three"
  24. ];
  25. //数组元素取值赋值
  26. arr1[0] = "one";
  27. arr2[2] = 3;
  28. console.log(arr1[0]);
  29. console.log(arr2[2]);
  30. console.log(arr3[1]);
  31. console.log(arr4[1][0]);
  32. //获取数组长度
  33. console.log(arr1.length);
  34. console.log(arr4.length);
  35. console.log(arr4[1].length);
  36. //访问超过数组下标的元素
  37. console.log(arr2[10]);
  38. console.log(arr2.length);
  39. //构造创建数组 很少用
  40. const arr5 = new Array();
  41. const arr6 = new Array(1, 2, 3);
  42. const arr7 = new Array(2);
  43. const arr8 = new Array("2");

8.2数组内容操作

方法 方法描述 修改数组或返回拷贝数组
push(返回新数组的长度),pop 创建一个栈(先进后出[LIFO]) 修改数组
unshift(返回新数组的长度),shift 创建一个队列(先进先出[FIFO]) 修改数组
concat 在数组末尾添加多个元素 返回数组拷贝
slice 获取子数组 返回数组拷贝
splice 在任意位置添加或删除元素
修改数组
copyWithin 剪切并替换数组元素
修改数组
fill 填充数组 修改数组
reverse 反转数组 修改数组
sort(传入函数来进行自定义排序) 数组排序 修改数组
  1. console.log("=============添加和删除数组元素===================");
  2. let arr = ["b", "c", "d"];
  3. console.log(arr.toString());
  4. //push和pop的作用分别是添加或者删除数组的最后一个元素
  5. //push和pop是栈操作
  6. console.log(arr.push("e"))
  7. console.log(arr.pop());
  8. //shift和unshift是删除和添加数组的第一个元素
  9. //shift和unshift队列操作
  10. console.log(arr.unshift("a"));
  11. console.log(arr.shift());
  12. console.log("=============合并追加数组===================");
  13. console.log(arr.concat(4, 5, 6).toString());
  14. console.log(arr.toString());
  15. console.log(arr.concat([4, 5, 6]).toString());
  16. console.log(arr.concat([4, 5], 6).toString());
  17. console.log(arr.concat([
  18. [4, 5], 6
  19. ]));
  20. console.log("=============截取数组===================");
  21. arr = [1, 2, 3, 4, 5];
  22. console.log(arr.slice(3).toString());
  23. console.log(arr.slice(2, 4).toString());
  24. console.log(arr.slice(-2).toString());
  25. console.log(arr.slice(1, -2).toString());
  26. console.log(arr.slice(-2, -1).toString());
  27. console.log(arr.toString());
  28. console.log("=============任意位置添加和删除元素===================");
  29. arr = [1, 5, 7]
  30. // 下标 删除个数 添加元素
  31. arr.splice(1, 0, 2, 3, 4).toString();
  32. console.log(arr.toString());
  33. arr.splice(5, 0, 6).toString();
  34. console.log(arr.toString());
  35. console.log(arr.splice(1, 2).toString());
  36. console.log(arr.toString());
  37. console.log(arr.splice(2, 1, 'a', 'b').toString());
  38. console.log(arr.toString());
  39. console.log("=============数组分割和替换===================");
  40. arr = [1, 2, 3, 4];
  41. // 目标 开始 结束
  42. console.log(arr.copyWithin(1, 2).toString());
  43. console.log(arr.toString());
  44. console.log(arr.copyWithin(2, 0, 2).toString());
  45. console.log(arr.copyWithin(0, -3, -1).toString());
  46. console.log("=============填充数组===================");
  47. arr = new Array(5).fill(1);
  48. console.log(arr.toString());
  49. console.log(arr.fill("a").toString());
  50. console.log(arr.fill("b", 1).toString());
  51. // 值 起始 结束
  52. console.log(arr.fill("c", 2, 4).toString());
  53. console.log(arr.fill(5.5, -4).toString());
  54. console.log(arr.fill(0, -3, -1).toString());
  55. console.log("=============数组的反转和排序===================");
  56. arr = [1, 2, 3, 4, 5];
  57. console.log(arr.reverse().toString());
  58. console.log(arr.toString());
  59. arr.sort();
  60. console.log(arr.toString());
  61. //指定排序函数
  62. //sort还允许指定一个排序函数
  63. arr = [{
  64. name: "Sunzane"
  65. }, {
  66. name: "Jim"
  67. }, {
  68. name: "Trevor"
  69. }, {
  70. name: "Amanda"
  71. }];
  72. let compare = function(a, b) { //比较函数
  73. if (a.name < b.name) {
  74. return -1;
  75. } else if (a.name > b.name) {
  76. return 1;
  77. } else {
  78. return 0;
  79. }
  80. }
  81. let compare1 = (a, b) => { //比较函数
  82. if (a.name < b.name) {
  83. return -1;
  84. } else if (a.name > b.name) {
  85. return 1;
  86. } else {
  87. return 0;
  88. }
  89. }
  90. console.log(arr.sort( (a, b) => { //比较函数
  91. if (a.name < b.name) {
  92. return -1;
  93. } else if (a.name > b.name) {
  94. return 1;
  95. } else {
  96. return 0;
  97. }
  98. }));

8.3数组的搜索

描述 方法
元素的下标 indexOf (简单的值),findIndex (复杂的值)
最后一个元素的下标 lastIndexOf ( 简单值)
元素本身 find
数组中符合条件的元素 some
数组中所有元素都符合给定条件 every
  1. const o = {
  2. name: "Jerry"
  3. };
  4. let arr = [1, 5, "a", o, true, 5, [1, 2], "9"];
  5. console.log("indexOf:"+arr.indexOf(5));
  6. console.log("lastIndexOf:"+arr.lastIndexOf(5));
  7. console.log("indexOf:"+arr.indexOf("a"));
  8. console.log("lastIndexOf:"+arr.lastIndexOf("a"));
  9. console.log("indexOf:"+arr.indexOf({
  10. name: "Jerry"
  11. }));
  12. console.log("indexOf:"+arr.indexOf(o));
  13. console.log("indexOf:"+arr.indexOf([1, 2]));
  14. console.log("indexOf:"+arr.indexOf("9"));
  15. console.log("indexOf:"+arr.indexOf(9));
  16. // searchvalue start
  17. console.log("indexOf:"+arr.indexOf("a", 5));
  18. console.log("indexOf:"+arr.indexOf(5, 5));
  19. console.log("lastIndexOf:"+arr.lastIndexOf(5, 4));
  20. console.log("lastIndexOf:"+arr.lastIndexOf(true, 3));
  21. arr = [{
  22. id: 5,
  23. name: "Judith"
  24. }, {
  25. id: 5,
  26. name: "Francis"
  27. }];
  28. //findIndex 返回下标,找不到返回-1
  29. console.log("findIndex:"+arr.findIndex(o => o.id === 5));
  30. console.log("findIndex:"+arr.findIndex(o => o.name === "Francis"));
  31. console.log("findIndex:"+arr.findIndex(o => o === 3));
  32. console.log("findIndex:"+arr.findIndex(o => o.id === 17));
  33. //find 返回数组中的元素,找不到返回undefined
  34. console.log("find:"+arr.find(o => o.id === 5));
  35. console.log("find:"+arr.find(o => o.id === 2));
  36. arr = [5, 7, 12, 15, 17];
  37. //判断某个值或者条件是否存在,存在为真,否则为假
  38. console.log("some:"+arr.some(x => x % 2 === 0));
  39. console.log("some:"+arr.some(x => Number.isInteger(Math.sqrt(x))));
  40. arr = [4, 6, 16, 36];
  41. //用于检测数组所有元素是否都符合指定条件
  42. console.log("every:"+arr.every(x => x % 2 === 0));
  43. console.log("every:"+arr.every(x => Number.isInteger(Math.sqrt(x))));

8.4数组转化

描述
方法
修改数组或返回拷贝数组
转化数组中的所有元素
map 返回数组拷贝
根据给定条件排除数组元素
filter 返回数组拷贝
把整个数组转化成另一种数组类型
reduce 返回数组拷贝
把元素转化成字符串并合并
join 返回数组拷贝

任何时候如果数组格式与所需要的格式不一样,都可以用map和filter
map和filter都不会修改原始数组,而是返回数组的拷贝

  1. const cart = [{
  2. name: "Widget",
  3. price: 9.95
  4. }, {
  5. name: "Gadget",
  6. price: 22.95
  7. }];
  8. //姓名
  9. const names = cart.map(x => x.name);
  10. console.log(names.toString());
  11. //价格
  12. const prices = cart.map(x => x.price);
  13. console.log(prices.toString());
  14. //价格8折
  15. const discountPrices = prices.map(x => x * 0.8);
  16. console.log(discountPrices.toString());
  17. //姓名全小写
  18. const lcNames = names.map(x=>x.toLowerCase());
  19. console.log(lcNames.toString());
  20. //name和prices 合并成cartNew x name i下标
  21. const cartNew = names.map((x,i)=>({name:x,price:prices[i]}));
  22. console.log(cartNew);
  1. //创建一副牌
  2. const cards = [];
  3. // 红桃 梅花 方块 黑桃
  4. for (let suit of ['H', 'C', 'D', 'S']) {
  5. for (let value = 1; value <= 13; value++) {
  6. cards.push({
  7. suit,
  8. value
  9. });
  10. }
  11. }
  12. //找到所有2的纸牌
  13. let val2 = cards.filter(c => c.value === 2);
  14. console.log(val2);
  15. //找到所有方块
  16. const valD = cards.filter(c => c.suit === 'D');
  17. console.log(valD);
  18. //找到所有花色牌
  19. const val10 = cards.filter(c => c.value > 10);
  20. console.log(val10);
  21. //找到所有红桃的花色牌
  22. let valH10 = cards.filter(c => c.value > 10 && c.suit === 'H');
  23. console.log(valH10);
  24. function cardToString(c) {
  25. const suits = {
  26. 'H': '\u2665',
  27. 'C': '\u2663',
  28. 'D': '\u2666',
  29. 'S': '\u2660'
  30. };
  31. const values = {
  32. 1: 'A',
  33. 11: 'J',
  34. 12: 'Q',
  35. 13: 'K'
  36. };
  37. for (let i = 2; i < 10; i++) {
  38. values[i] = i;
  39. }
  40. return values[c.value] + suits[c.suit];
  41. }
  42. //找到所有2的纸牌
  43. val2 = cards.filter(c => c.value === 2).map(cardToString);
  44. console.log(val2);
  45. //找到所有红桃的花色牌
  46. valH10 = cards.filter(c => c.value > 10 && c.suit === 'H').map(cardToString);
  47. console.log(valH10);

reduce可以转化整个数组。经常被用于将一个数组归纳成一个单独的值。
比如,对数组所有元素求和或者计算它们的平均值等

  1. const arr = [5, 7, 2, 4];
  2. //arr.reduce(function(prev,cur,index,arr){
  3. // ...
  4. //}, init);
  5. //prev 必需 cur 必需 剩下都是可选
  6. const sum = arr.reduce((a, x) =>{
  7. console.log(a); // init 初始 累计的值
  8. console.log(x);
  9. return a + x
  10. }, 0);
  11. console.log(sum);
  12. const words = ["Beachball", "Rodeo", "Angel",
  13. "Aardvark", "Xylophone", "November", "Chocolate",
  14. "Papaya", "Uniform", "Joker", "Clover", "Bali"
  15. ];
  16. //首字母相同放一个数组里
  17. const alphabetical = words.reduce((a, x) => {
  18. if (!a[x[0]]) {
  19. a[x[0]] = [];
  20. }
  21. a[x[0]].push(x);
  22. return a;
  23. }, {});
  24. console.log(alphabetical);
  25. const data = [3.3, 5, 7.2, 12, 4, 6, 10.3];
  26. //半数值算法
  27. const stats = data.reduce((a, x) => {
  28. a.N++;
  29. let delta = x - a.mean;
  30. a.mean += delta / a.N;
  31. a.M2 += delta * (x - a.mean);
  32. return a;
  33. }, {
  34. N: 0,
  35. mean: 0,
  36. M2: 0
  37. });
  38. if (stats.N > 2) {
  39. stats.variance = stats.M2 / (stats.N - 1);
  40. stats.stdev = Math.sqrt(stats.variance);
  41. console.log(stats.stdev);
  42. }