数组的声明两种方式

  1. var arr01 = [12,"hello",true];
  2. console.log(arr01,typeof arr01); // "object"
  3. var arr02 = new Array(12,"hello",true);
  4. console.log(arr01,typeof arr02);
  5. console.log(arr01.length);

数组的常用方法

image.png

  1. // 1 插入和删除
  2. arr.push("a");
  3. arr.push([111,222]);
  4. console.log(arr);
  5. var ret = arr.pop();
  6. console.log(ret);
  7. console.log(arr);
  8. arr.unshift(100);
  9. console.log(arr);
  10. arr.shift();
  11. console.log(arr);
  12. // 2 反转和排序
  13. var arr02 = [1,4,3,6,2];
  14. var arr02 = [1,4,10,6,2,100];
  15. arr02.reverse();
  16. console.log(arr02);
  17. function sort_num(a,b){
  18. return a-b
  19. }
  20. arr02.sort(sort_num);
  21. console.log(arr02);
  22. // splice方法
  23. var arr = [1,2,3,4,5];
  24. // (1)删除多个元素
  25. arr.splice(2,2);
  26. console.log(arr);
  27. // (2) 添加多个元素
  28. // arr.splice(2,0,100,101,102);
  29. // console.log(arr);
  30. // (3) 替换多个元素
  31. // arr.splice(2,2,33,44);
  32. // console.log(arr);
  33. var arr1 = [1,2,3];
  34. var arr2 = [4,5,7];
  35. var ret = arr1.concat(arr2);
  36. console.log( ret );
  37. // join方法
  38. var s = "zhangsan li wangwu";
  39. var ret = s.split(" ");
  40. console.log(ret);
  41. var s2 = ret.join("-");
  42. console.log(s2);
  43. console.log(arr1.includes(2));
  44. console.log(arr1.indexOf(3));
  45. console.log(Array.isArray(arr1));
  46. // 切片操作
  47. arr3 = [111,222,333,444,555,666];
  48. console.log(arr3.slice(1,3));
  49. console.log(arr3.slice(1,-1));
  50. console.log(arr3.slice(1));
  51. console.log(arr3.slice());
  52. console.log(arr3.slice(-3,-2));
  53. console.log(arr3.slice(-2,-3)); // []
  54. // 数组循环
  55. for (var i=0;i<arr3.length;i++){
  56. // 循环体
  57. console.log(i,arr3[i])
  58. }