Array 数组

重要通知

类目简介

基本概况

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array

基础数组对象

const array = [0, 10, 7, 3, 15];

console.log(array.constructor);            // [Function: Array]
console.log(array.constructor === Array);  // true
console.log(array.length);                 // 5

// 将一个或多个元素添加到数组的末尾,并返回该数组的新长度。
array.push(value);      // 在数组尾部添加数据,[改变原数组]
array.pop();            // 删除数组尾部的数据,并返回删除的数据,[改变原数组]
array.shift();     // 删除数组头部的数据,并返回删除的数据,[改变原数组]
array.unshift(value);        // 向数组的开头添加一个或更多元素,并返回新的长度。[改变原数组]

console.log(array.concat(['Hello']));  // 合并数组并返回新数组。输出结果:[ 0, 10, 7, 3, 15, 'Hello' ]
console.log(array.indexOf(2));  // 查找数组中是否存在指定内容并返回在数组中第一次出现的位置(从0开始),不存在时返回-1。输出结果:-1
console.log(array.toString());  // 将数组转换为字符串。输出结果:0,10,7,3,15
console.log(array.join());  // 将数组元素连接成字符串,省略参数则默认为','。输出结果:0,10,7,3,15
  • 使用Array和[]创建数组的区别
使用new Array比使用[]的时间长
console.time('using[]')
for(var i=0; i<2000000; i++){var arr = []};
console.timeEnd('using[]')
 
console.time('using new')
for(var i=0; i<2000000; i++){var arr = new Array};
console.timeEnd('using new')

ES6

Array.from

/**
 * Array.from() 静态方法从可迭代或类数组对象创建一个新的浅拷贝的数组实例。
 * 
 * Array.from(arrayLike[, mapFn[, thisArg]]):将类数组对象或可迭代对象转化为数组
 * arrayLike:想要转换的类数组对象或可迭代对象  
 * mapFn:可选,map 函数,用于对每个元素进行处理,放入数组的是处理后的元素 
 * thisArg:可选,用于指定 map 函数执行时的 this 对象  
 */
console.log(Array.from([1, 2])); // [1, 2]  
console.log(Array.from([1, , 3])); // [1, undefined, 3]  
console.log(Array.from([1, , 3], (dx) => { return dx + 1; }));  //[ 2, NaN, 4 ]   

/**
 * 类数组对象,例如 document.getElementsByTagName("*") HTMLCollection
 * 一个类数组对象必须含有 length 属性,且元素属性名必须是数值或者可转换为数值的字符
 */
let arr = Array.from({
  0: '1',
  1: '2',
  2: 3,
  length: 3
});


// 可迭代对象
// 转换 map
// 转换 set
let arr = [1, 2, 3];
let set = new Set(arr);
console.log(Array.from(set));  //[ 1, 2, 3 ]
// 转换字符串
let str = 'abc';
console.log(Array.from(str)); // ["a", "b", "c"]
/**
 * Array.of()
 * 将参数中所有值作为元素形成数组
 */
console.log(Array.of(1, 2, 3));  //[ 1, 2, 3 ]















/**
 * find():查找数组中符合条件的元素,若有多个符合条件的元素,则返回第一个元素
 * 参数1:回调函数 
 * 参数2(可选):指定回调函数中的 this 值
 */
let arr = Array.of(1, 2, 3, 4);
console.log(arr.find(item => item > 2)); // 3  
// 数组空位处理为 undefined  
console.log([, 1].find(n => true)); // undefined  

/**
 * findIndex():查找数组中符合条件的元素索引,若有多个符合条件的元素,则返回第一个元素索引
 * 参数1:回调函数 
 * 参数2(可选):指定回调函数中的 this 值 
 */
let arr = Array.of(1, 2, 1, 3);
console.log(arr.findIndex(item => item = 1)); // 0    

/**
 * fill():将一定范围索引的数组元素内容填充为单个指定的值
 * 参数1:用来填充的值
 * 参数2:被填充的起始索引 
 * 参数3(可选):被填充的结束索引,默认为数组末尾  
 */
let arr = Array.of(1, 2, 3, 4);
console.log(arr.fill(0, 1, 2)); // [1, 0, 3, 4]  

/**
 * copyWithin(target, start, end):将一定范围索引的数组元素修改为此数组另一指定范围索引的元素, 从数组的指定位置拷贝元素到数组的另一个指定位置中
 * target:必需。复制到指定目标索引位置。 
 * start:可选。元素复制的起始位置。  
 * end:可选(不包括该值)。停止复制的索引位置 (默认为 array.length)。如果为负值,表示倒数。 
 */
var fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits.copyWithin(1, 0, 1));  //[ 'Banana', 'Banana', 'Apple', 'Mango' ]  


// entries():	返回遍历键值对
for (let [key, value] of ['a', 'b'].entries()) {
  console.log(key, value);  //0 'a' | 1 'b'  
}

// keys():	返回数组的可迭代对象,包含原始数组的键(key)
for (let key of ['a', 'b'].keys()) {
  console.log(key);  // 0 | 1  
}

// values():遍历键值
for (let value of ['a', 'b'].values()) {
  console.log(value);  // "a" | "b"  
}

// includes():判断一个数组是否包含一个指定的值
[1, 2, 3].includes(1);  // true


// flat():嵌套数组转一维数组
console.log([1, [2, 3]].flat()); // [1, 2, 3]  
// 指定转换的嵌套层数  
console.log([1, [2, [3, [4, 5]]]].flat(2)); // [1, 2, 3, [4, 5]]  
// 不管嵌套多少层  
console.log([1, [2, [3, [4, 5]]]].flat(Infinity)); // [1, 2, 3, 4, 5]  
// 自动跳过空位  
console.log([1, [2, , 3]].flat()); // [1, 2, 3]  


/** 
 * flatMap(fn, scope):先对数组中每个元素进行了的处理,再对数组执行 flat() 方法
 * 遍历函数,该遍历函数可接受3个参数:当前元素、当前元素索引、原数组
 * 指定遍历函数中 this 的指向
 */
console.log([1, 2, 3].flatMap(n => [n * 2], this));
// [2, 4, 6]  

ES5

array.reduce | 数组不能为空

对数组中的每个元素按序执行一个提供的 reducer 函数,每一次运行 reducer 会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。

/**
 * Array.reduce(function(accumulator, currentValue, currentIndex, arr), initialValue)
 * accumulator	必需。初始值, 或者计算结束后的返回值。在第一次调用时,如果指定了 initialValue 则为指定的值,否则为 array[0] 的值。
 * currentValue	必需。当前元素的值。在第一次调用时,如果指定了 initialValue,则为 array[0] 的值,否则为 array[1]。
 * currentIndex	可选。在数组中的索引位置。在第一次调用时,如果指定了 initialValue 则为 0,否则为 1。
 * arr	可选。调用了 reduce() 的数组本身。
 */
console.log([0].reduce(function (accumulator, currentValue) { return accumulator + currentValue }));  // 0
console.log([0, 2].reduce(function (accumulator, currentValue) { return accumulator + currentValue }));  // 2
console.log([0, 2, 3].reduce(function (accumulator, currentValue) { return accumulator + currentValue }));  // 5


var array = [4, 5, 1, 8];
let result = array.reduce((
  accumulator, 
  currentValue, 
  currentIndex, 
  arr
) => {
	return accumulator;
});

console.log(result);  //4


let result = array.reduce((
  accumulator, 
  currentValue, 
  currentIndex, 
  arr
) => {
	return accumulator + currentValue;
});

console.log(result);  //18

Array.splice

/**
 * 添加、替换或删除
 * 
 * Array.splice(start, count, value):从数组中添加、替换或删除元素, 会改变原始数组
 * start:替换、插入的开始位置
 * count:替换、插入的数组长度,负数时与0一样
 * value:替换、插入的数组值
 */
// 添加:注意第二个参数count,如果为0,则实现添加功能
let fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, 'nage', 'sex');
fruits.splice(2, 0, ...(['nage', 'sex']));
console.log(fruits);  //[ 'Banana', 'Orange', 'nage', 'sex', 'Apple', 'Mango' ]

// 替换:注意第二个参数count,如果不为0,则替换功能
let fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 1, 'nage', 'sex');
console.log(fruits);  //[ 'Banana', 'Orange', 'nage', 'sex', 'Mango' ]

// 删除:如果第三个参数缺失,则为删除功能
let fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 1);
console.log(fruits);  //[ 'Banana', 'Orange', 'Mango' ]
fruits.splice(2);  // 删除第二数后面的所有数据




/**
 * 数组元素
 * 删除数组元素:数组一旦被定义就不能被删除,使用delete运算符智能删除数组元素的值
 * 数组元素的个数:array.length
 */


/**
 * Array.slice(start, end):返回数组中的一部分,默认为克隆全部
 * start:开始序列
 * end,结束序列,不包括该序列,默认为从start到最后
 * 
 */
const studentList = [{ name: '张三' }, { name: '张思' }, { name: '张数' }, { name: '张苏' }];
console.log(studentList.slice(0, 2)); // [ { name: '张三' }, { name: '张思' } ]
console.log(studentList.slice(1, 2)); // [ { name: '张思' } ]


// array.reverse():颠倒数组中的元素
var fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits.reverse());  //Mango,Apple,Orange,Banana


// array.sort():将数组元素排序,调用该方法时没有使用参数,按照字符编码的顺序进行排序
let b = [4, 5, 1, 8, 3, 9, 2, 6, 4, 7, 11, 23, 16];

// 不传参,默认为按照字符编码的顺序进行排序
console.log(b.sort());  //[ 1, 11, 16, 2, 23, 3, 4, 4, 5, 6, 7, 8, 9 ]
// 正序
console.log(array.sort(function (a, b) {
	return a - b;  //[1, 2, 3, 4, 4, 5, 6, 7, 8, 9, 11, 16, 23]
}));

// 反序
console.log(array.sort(function (a, b) {
	return b - a;  //[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
}));

// 乱序
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(array.sort(function (a, b) {
	var lab = (Math.random() > 0.5) ? 1 : -1;
	return (b - a) * lab;
}));




Array.toLocaleString(); // 转换为当地字符串
Array.isArray(months);  // 判断months是否为数组


/**
 * Array.forEach(currentValue, index, array)  //IE8以下(含ie8)不存在该方法,若需要使用,需为原型添加该方法
 * @param:value,数组中数值
 * @param:index,数组中索引值
 * @param:fullArray,数组
 */
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November"];
months.forEach(function (value, index, array) {
	console.log(value + " is month number " + (index + 1) + " of " + fullArray.length);
});


/**
 * Array.filter(currentValue, index, array)
 * 创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素
 */
let array = [0, 1, 2];
let arr1 = array.filter((currentValue, index, array) => {
	return currentValue > 1;
});
console.log(arr1);  //2


/**
 * Array.map(currentValue, index, array)
 * 功能:返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值;
 * 语法:Array.map(function(currentValue, index, array) { }, [thisValue])
 * currentValue:当前元素的值
 * index:当期元素的索引值
 * array:当期元素属于的数组对象
 * thisValue:对象作为该执行回调时使用,传递给函数,用作 "this" 的值;如果省略了 thisValue ,"this" 的值为 "undefined"
 * 
 */
const result = [{ name: '', count: 1 }, { name: '', count: 1 }];
const hell = result.map((item) => {
	item.name = '111';
	return item;
});
console.log(hell);

var array = new Array(100);
var rst = array.join(',').split(',').map(function (item, index) {
	return index;
});
console.log(rst);



ArrayBuffer与TypedArray数组缓冲区

简介与核心思想

数组缓冲区是内存中的一段地址

代码示例

    let buffer = new ArrayBuffer(10);
    console.log(buffer.byteLength);  //10
    console.log(buffer.slice(1, 3));  //2

视图:视图是用来操作内存的接口

视图可以操作数组缓冲区或缓冲区字节的子集,并按照其中一种数值数据类型来读取和写入数据 DataView 类型是一种通用的数组缓冲区视图,其支持所有8种数值型数据类型

	let buffer = new ArrayBuffer(10);
			dataView = new DataView(buffer); 
	dataView.setInt8(0,1);
	console.log(dataView.getInt8(0)); // 1
	// 通过设定偏移量(参数2)与长度(参数3)指定 DataView 可操作的字节范围
	let buffer1 = new ArrayBuffer(10);
			dataView1 = new DataView(buffer1, 0, 3);
	dataView1.setInt8(5,1); // RangeError

类型数组

	let view2 = new Int16Array([1, 2]),
			view3 = new Int32Array(view2),
			view4 = new Int16Array(new Set([1, 2, 3])),
			view5 = new Int16Array([1, 2, 3]),
			view6 = new Int16Array(arr);

	console.log(view2 .buffer === view3.buffer); // false
	console.log(view4.byteLength); // 6
	console.log(view5.byteLength); // 6
	console.log(view6.byteLength); // 6

可索引的集合对象

MDN:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/TypedArray

可索引的集合对象

功能:这些对象表示按照索引值来排序的数据集合,包括数组和类型数组,以及类数组结构的对象。

包含对象

Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array BigInt64Array BigUint64Array

TypedArray 对象

一个泛概念 描述一个底层的二进制数据缓存区的一个类似数组(array-like)视图 没有名为 TypedArray的全局对象,也没有一个名为的 TypedArray构造函数

new TypedArray(); // ES2017中新增 new TypedArray(length); new TypedArray(typedArray); new TypedArray(object); new TypedArray(buffer [, byteOffset [, length]]);

TypedArray()指的是以下的其中之一

Int8Array(); Uint8Array(); Uint8ClampedArray(); Int16Array(); Uint16Array(); Int32Array(); Uint32Array(); Float32Array(); Float64Array();

10 Heap View Types

View Type Element Size (Bytes) Load Type Store Types Uint8Array 1 intish intish Int8Array 1 intish intish Uint16Array 2 intish intish Int16Array 2 intish intish Uint32Array 4 intish intish Int32Array 4 intish intish Float32Array 4 float? floatish, double? Float64Array 8 double? float?, double?

ArrayBuffer二进制对象

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer

简介与核心思想

ArrayBuffer对象、TypedArray视图和DataView视图是 JavaScript 操作二进制数据的一个接口。

arraybuffer与blob 相互转换

  var buffer = new ArrayBuffer(16);
  var blob = new Blob([buffer]);

Blob转ArrayBuffer

  var blob = new Blob([1,2,3,4,5]);
  var reader = new FileReader();
  reader.onload = function() {
    console.log(this.result);
  }
  reader.readAsArrayBuffer(blob);

UTF-8 ArrayBuffer和字符串之间的转换

  function stringToUint(string) {
    var string = btoa(unescape(encodeURIComponent(string))),
        charList = string.split(''),
        uintArray = [];
    for (var i = 0; i < charList.length; i++) {
        uintArray.push(charList[i].charCodeAt(0));
    }
    return new Uint8Array(uintArray);
  }

  function uintToString(uintArray) {
    var encodedString = String.fromCharCode.apply(null, uintArray),
        decodedString = decodeURIComponent(escape(atob(encodedString)));
    return decodedString;
  }

arraybuffer


名称 占用字节 描述

Int8Array 1 8位二补码有符号整数 Uint8Array 1 8位无符号整数 Uint8ClampedArray 1 8位无符号整型固定数组(数值在0~255之间) Int16Array 2 16位二补码有符号整数 Uint16Array 2 16位无符号整数 Int32Array 4 32 位二补码有符号整数 Uint32Array 4 32 位无符号整数 Float32Array 4 32 位 IEEE 浮点数 Float64Array 8 64 位 IEEE 浮点数

API

  const array = [0, 10, 7, 3, 15];
  const arr1 = [10, 0, 122];
  const arr2 = [88, 99, 44];
  const arr3 = [
    [902, 100, 786, 67],
    [902, 100, 786, 67],
    [902, 100, 786, 67]
  ];
  const arr4 = [
    { label: '在数组尾部添加数据', value: 0, },
    { label: '删除数组尾部的数据', value: 1, },
    { label: '在数组头部添加数组', value: 2, },
    { label: '删除数组头部的数据', value: 3, }
  ];


  [array].concat(arr1, [...]);   // 合并数组,并返回合并后的数组
  [array].copyWithin();            // 从数组的指定位置拷贝元素到数组的另一个指定位置中

  // 枚举
  [array].entries();
  [array].keys();
  [array].values();

  // 检索
  [array].find((item) => { return item.value == '' } );                 // 检索数组中符合条件的第一个元素的值。
  [array].findIndex((key) => { return key > 15 });                      // 检索数组中符合条件的第一个元素的位置(从0开始)。
  [array].includes(value);        // 判断一个数组是否包含一个指定的值,如果是返回 true,否则false。
  [array].indexOf();              // 搜索数组中的元素,并返回它所在的位置,从0开始。
  [array].lastIndexOf();          // 搜索数组中的元素,并返回它最后出现的位置,从0开始。
  [array].every();                // 检测数组所有元素是否都符合指定条件
  [array].filter((key) => key.value);               // 检索根据过滤条件返回数值

  // 遍历
  [array].forEach();

  // 处理数组
  [array].map();                  // 通过指定函数处理数组的每个元素,并返回处理后的数组。
  [array].reduce();              // 将数组元素计算为一个值(从左到右)。
  [array].reduceRight();         // 将数组元素计算为一个值(从右到左)。

  [array].isArray();             // 判断对象是否为数组。
  
  // 操作
  [array].fill();                // 将一个固定值替换数组的元素。
  [array].flat();
  [array].flatMap();  
  [array].join('指定分隔符');                // 把数组的所有元素放入一个字符串。



  [array].slice();
  [array].splice();
  [array].some();
  [array].valueOf();             // 返回 Array 对象的原始值。

  [array].reverse();             // 反转数组的元素顺序。
  [array].sort();                // 对数组的元素进行排序。

  [array].toLocaleString();
  [array].toString();
  [array].Symbol(Symbol.iterator);
  [array].Symbol(Symbol.unscopables);

TypedArray 对象

一个类型化数组(TypedArray)对象描述了一个底层的二进制数据缓冲区(binary data buffer)的一个类数组视图(view)。

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/TypedArray

简介

类型 单个元素值的范围 单个元素大小(bytes) 描述 Web IDL 类型 C 语言中的等价类型

Int8Array -128 to 127 1 8 位二进制有符号整数 byte int8_t Uint8Array 0 to 255 1 8 位无符号整数(超出范围后从另一边界循环) octet uint8_t Uint8ClampedArray 0 to 255 1 8 位无符号整数(超出范围后为边界值) octet uint8_t Int16Array -32768 to 32767 2 16 位二进制有符号整数 short int16_t Uint16Array 0 to 65535 2 16 位无符号整数 unsigned short uint16_t Int32Array -2147483648 to 2147483647 4 32 位二进制有符号整数 long int32_t Uint32Array 0 to 4294967295 4 32 位无符号整数 unsigned long uint32_t Float32Array 1.2×10-38 to 3.4×1038 4 32 位 IEEE 浮点数(7 位有效数字,如 1.1234567) unrestricted float float Float64Array 5.0×10-324 to 1.8×10308 8 64 位 IEEE 浮点数(16 有效数字,如 1.123...15) unrestricted double double BigInt64Array -263 to 263-1 8 64 位二进制有符号整数 bigint int64_t (signed long long) BigUint64Array 0 to 264-1 8 64 位无符号整数 bigint uint64_t (unsigned long long)

TypedArray属性

TypedArray方法

语法

  new Int8Array(length);
  new Int8Array(typedArray);
  new Int8Array(object);
  new Int8Array(buffer [, byteOffset [, length]]);

代码示例

  new Int8Array();   // Int8Array(0) []
  new Int8Array(3);  // Int8Array(3) [ 0, 0, 0 ]

遍历

  • for...of:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/for...of
  • for...in:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/for...in

for...of循环

for...of 语句遍历可迭代对象定义要迭代的数据。 用于替代 for..in 和 forEach() , 并且支持新的迭代协议。它可用于迭代常规的数据类型:Array、Map、Set、String、TypedArray、arguments、DOM collection对象等

  var map = new Map();
  map.set(0, "zero");
  map.set(1, "one");
  for (var [key, value] of map) {
    console.log(key + " = " + value);  // 0 = zero | 1 = one
  }
  for (var item of map) {
    console.log(item);  // [ 0, 'zero' ] | [ 1, 'one' ]
  }

for...in

for...in 语句以任意顺序迭代对象的可枚举属性。 以任意顺序遍历一个对象的除Symbol以外的可枚举属性,包括继承的可枚举属性。

  const object = { a: 1, b: 2, c: 3 };
  for (const property in object) {
    console.log(`${property}: ${object[property]}`);  // "a: 1"  "b: 2"  "c: 3"
  }  

Array.prototype.forEach()

arr.forEach(callback(currentValue [, index [, array]])[, thisArg]) 不能终止阻断执行 当原有数组对象是对象数组时,forEach可以改变原有数组对象 [非对象数组则不能改变]

Array.prototype.every()

校验指定数组中是否所有元素皆满足设定条件,并返回布尔值。

  const result = [0, 100, 55, 88, 25].every((value) => {
    return value < 10;
  });
  console.log(`输出结果:`, result);  // 输出结果:false

Array.prototype.some()

校验指定数组中是否至少存在一个元素满足设定条件,并返回布尔值。

  const result = [0, 100, 55, 88, 25].some((value) => {
    return value < 10;
  });
  console.log(`输出结果:`, result);  // 输出结果: true

Array.prototype.find()

校验指定数组中是否至少存在一个元素满足设定条件,并返回满足设定条件的第一个元素,如果不存在则返回undefined。

  const result = [0, 100, 55, 88, 25].find((value) => {
    return value > 100;
  });
  console.log(`输出结果:`, result);  // 输出结果: undefined

Array.prototype.findIndex()

校验指定数组中是否存在满足设定条件的元素,并返回第一个元素的索引(从0开始),如果不存在则返回-1。

  const result = [0, 100, 55, 88, 25].findIndex((value) => {
    return value > 100;
  });
  console.log(`输出结果:`, result);  // 输出结果: -1

Array.sort()

module.exports = async function() {
  console.log("|-----" + "排序" + "-----FILE_URL: " + __filename);

  //业务模型
  await init();

}

async function init() {
  //Sort();
  //ChinaSort();
  //LetterSort();
  LetterFallSort();
  //NumberSort();
  //NumberRiseSort();
  //NumberFallSort();
}

async function Sort() {
  let Students = ['张飞', '李四', '刘备', '郭嘉', '曹操'];

  let result = Students.sort();
  console.log(result);
}

async function ChinaSort() {
  let Students = ['张飞', '李四', '刘备', '郭嘉', '曹操'];

  //中文排序-拼音首字母
  let result = Students.sort((a, b)=> {
    return a.localeCompare(b, 'zh-Hans-CN', {sensitivity: 'accent'});
  });
  console.log(result);
  //[ '刘备', '张飞', '曹操', '李四', '郭嘉' ]
}

async function LetterSort() {
  let Letter = ['Z', 'A', 'U', 'G', 'C', 'T', 'M'];

  //字母排序-升序
  let result = Letter.sort();
  console.log(result);
  //[ 'A', 'C', 'G', 'M', 'T', 'U', 'Z' ]
}

async function LetterFallSort() {
  let Letter = ['Z', 'A', 'U', 'G', 'C', 'T', 'M'];

  //字母排序-降序
  let result = Letter.sort((a, b)=> {
    return b-a;
  });
  console.log(result);
  //[ 'A', 'C', 'G', 'M', 'T', 'U', 'Z' ]
}

async function NumberSort() {
  let count = [9, 5, 8, 1, 4, 2];

  //数字排序-升序
  let result = count.sort();
  console.log(result);
  //[ 1, 2, 4, 5, 8, 9 ]

  let array = [9, 5, 8, 1, 4, 2, 11, 90, 12, 67, 33];

  //不加回调函数, 只能排下标10以内的数组
  let out = array.sort();
  console.log(out);
  //[ 1, 11, 12, 2, 33, 4, 5, 67, 8, 9, 90 ]
}

async function NumberRiseSort() {
  let count = [9, 5, 8, 1, 4, 2, 11, 90, 12, 67, 33];

  //数字排序-升序
  let result = count.sort((a, b)=> {
    return a-b;
  });
  console.log(result);
  //[ 1, 2, 4, 5, 8, 9 ]
}

async function NumberFallSort() {
  let count = [9, 5, 8, 1, 4, 2, 11, 90, 12, 67, 33];

  //数字排序-降序
  let result = count.sort((a, b)=> {
    return b-a;
  });
  console.log(result);
  //[ 90, 67, 33, 12, 11, 9, 8, 5, 4, 2, 1 ]
}

Last Updated:
Contributors: 709992523, Eshen