js内置对象——Array

Array

简介

JS的数组与常规的静态语言不同,JS的数组元素可以是不同的类型。而且索引也不一定是连续的。

数组长度 length

数组索引从0开始,数组的length属性为该数组最大索引+1。

var cats = [];
cats[30] = ['Dusty'];
console.log(cats.length); // 31

开发者也可以手动修改length的值,修改length的值会改变数组

var cats = ['Dusty', 'Misty', 'Twiggy'];
console.log(cats.length); // 3

cats.length = 2;
console.log(cats); // logs "Dusty,Misty" - Twiggy has been removed

cats.length = 0;
console.log(cats); // logs nothing; the cats array is empty

cats.length = 3;
console.log(cats); // [undefined, undefined, undefined]

遍历数组

  • for
  • for-of
  • forEach

常用方法

增、删

  • push() 在数组末尾添加一个或多个元素,并返回数组操作后的长度。
  • pop() 从数组移出最后一个元素,并返回该元素。
  • shift() 从数组移出第一个元素,并返回该元素。
  • unshift(...) 在数组开头添加一个或多个元素,并返回数组的新长度。
  • splice(index, count_to_remove, addElement1, addElement2, ...)从数组移出一些元素,(可选)并替换它们。
var myArray = new Array ("1", "2", "3", "4", "5");
myArray.splice(1, 3, "a", "b", "c", "d");
// myArray is now ["1", "a", "b", "c", "d", "5"]
// This code started at index one (or where the "2" was),
// removed 3 elements there, and then inserted all consecutive
// elements in its place.

  • reverse() 颠倒数组元素的顺序:第一个变成最后一个,最后一个变成第一个。

查找

排序

  • sort() 给数组元素排序
var myArray = new Array("Wind", "Rain", "Fire");
myArray.sort();
// sorts the array so that myArray = [ "Fire", "Rain", "Wind" ]

sort()可以带回调函数来决定怎么比较数组元素。

var sortFn = function(a, b){
  if (a[a.length - 1] < b[b.length - 1]) return -1;
  if (a[a.length - 1] > b[b.length - 1]) return 1;
  if (a[a.length - 1] == b[b.length - 1]) return 0;
}
myArray.sort(sortFn);
// sorts the array so that myArray = ["Wind","Fire","Rain"]
  • 如果 a 小于 b ,返回 -1(或任何负数)
  • 如果 a 大于 b ,返回 1 (或任何正数)
  • 如果 a 和 b 相等,返回 0。
posted @ 2020-12-24 09:23  ccbbzz  阅读(60)  评论(0编辑  收藏  举报