UNPKG

jscoding

Version:

A envirement for coding and debugging javascript language.

715 lines (446 loc) 16.7 kB
# Javascript API ## 数组方法 ### toString & join - .toString() JavaScript 方法 toString() 把数组转换为数组值(逗号分隔)的字符串。 ```js var elements = ['Fire', 'Air', 'Water']; console.log(elements.toString()); // expected output: "Fire,Air,Water" ``` > 注:所有 JavaScript 对象都拥有 toString() 方法。 - .join() join() 方法也可将所有数组元素结合为一个字符串。 它的行为类似 toString(),但是您还可以规定分隔符: ```js var elements = ['Fire', 'Air', 'Water']; console.log(elements.join('-')); // expected output: "Fire-Air-Water" ``` ### Pop & Push 在处理数组时,删除元素和添加新元素是很简单的。 Popping 和 Pushing 指的是:从数组*弹出*项目,或向数组*推入*项目。 - .pop() pop() 方法从数组中删除最后一个元素,返回“被弹出”的值: ```js var plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato']; console.log(plants.pop()); // expected output: "tomato" console.log(plants); // expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"] ``` - .push() push() 方法(在数组结尾处)向数组添加一个新的元素,返回新数组的长度: ```js var animals = ['pigs', 'goats', 'sheep']; console.log(animals.push('cows')); // expected output: 4 console.log(animals); // expected output: ["pigs", "goats", "sheep", "cows"] ``` ### shift & unshift 位移与弹出等同,但处理首个元素而不是最后一个。 - .shift() shift() 方法会删除首个数组元素,并把所有其他元素“位移”到更低的索引,返回被“位移出”的元素: ```js var fruits = ["Banana", "Orange", "Apple", "Mango"]; console.log(fruits.shift()); // expected output: "Banana" console.log(fruits); // expected output: ["Orange", "Apple", "Mango"] ``` - .unshift() unshift() 方法(在开头)向数组添加新元素,并“反向位移”旧元素,返回新数组的长度: ```js var fruits = ["Banana", "Orange", "Apple", "Mango"]; console.log(fruits.unshift("Lemon")); // expected output: 5 console.log(fruits); // expected output: ["Banana", "Orange", "Apple", "Mango", "Lemon")] ``` ### delete 既然 JavaScript 数组属于对象,其中的元素就可以使用 JavaScript delete 运算符来*删除*: ```js var fruits = ["Banana", "Orange", "Apple", "Mango"]; delete fruits[0]; console.log(fruits[0]); // expected output: undefined ``` > 注:使用 delete 会在数组留下未定义的空洞。请使用 pop() 或 shift() 取而代之。 ### splice splice() 方法可用于向数组添加新项,返回一个包含已删除项的数组: > 第一个参数定义了应添加新元素的位置(拼接)。 > > 第二个参数定义应删除多少元素。 > > 其余参数定义要添加/替换的新元素。 ```js var fruits = ["Banana", "Orange", "Apple", "Mango"]; console.log(fruits.splice(1, 0, "Lemon", "Kiwi"));// inserts at index 1 // expected output: [] console.log(fruits); // expected output: ["Banana", "Lemon", "Kiwi", "Orange", "Apple", "Mango"] console.log(fruits.splice(2, 1));// delete 1 element at index 2 // expected output: ["Kiwi"] console.log(fruits); // expected output: ["Banana", "Lemon", "Orange", "Apple", "Mango"] console.log(fruits.splice(3, 1, "Kiwi"));// replaces 1 element at index 3 // expected output: ["Apple"] console.log(fruits); // expected output: ["Banana", "Lemon", "Orange", "Kiwi", "Mango"] ``` ### concat concat() 方法通过合并(连接)现有数组来创建一个新数组: ```js var array1 = ['a', 'b', 'c']; var array2 = ['d', 'e', 'f']; console.log(array1.concat(array2)); // expected output: ["a", "b", "c", "d", "e", "f"] ``` > 注: > > concat() 方法不会更改现有数组。它总是返回一个新数组。 > > concat() 方法可以使用任意数量的数组参数: ``` var arr1 = ["Cecilie", "Lone"]; var arr2 = ["Emil", "Tobias", "Linus"]; var arr3 = ["Robin", "Morgan"]; var myChildren = arr1.concat(arr2, arr3); // 将arr1、arr2 与 arr3 连接在一起 ``` concat() 方法也可以将值作为参数: ```js const letters = ['a', 'b', 'c']; const alphaNumeric = letters.concat(1, [2, 3]); console.log(alphaNumeric); // expected output: ['a', 'b', 'c', 1, 2, 3] ``` ### slice slice() 方法用数组的某个片段切出新数组: 本例从数组元素 1"Orange")开始切出一段数组: ```js var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; var citrus = fruits.slice(1); var animals = ['ant', 'bison', 'camel', 'duck', 'elephant']; console.log(fruits.slice(2)); // expected output: Array ["Lemon", "Apple", "Mango"] console.log(fruits.slice(2, 4)); // expected output: Array ["Apple", "Mango"] console.log(fruits.slice(1, 5)); // expected output: Array ["Orange", "Lemon", "Apple", "Mango"] ``` > 注:slice() 方法创建新数组,不会从源数组中删除任何元素。 ## 数组排序 ### 字符排序 sort() 方法以字母顺序对数组进行排序: ```js var months = ['March', 'Jan', 'Feb', 'Dec']; months.sort(); console.log(months); // expected output: Array ["Dec", "Feb", "Jan", "March"] var array = [1, 30, 4, 21, 100000]; array.sort(); console.log(array); // expected output: Array [1, 100000, 21, 30, 4] ``` ### 数字排序 默认地,sort() 函数按照*字符串*顺序对值进行排序。 该函数很适合字符串("Apple" 会排在 "Banana" 之前)。 不过,如果数字按照字符串来排序,则 "25" 大于 "100",因为 "2" 大于 "1"。 正因如此,sort() 方法在对数值排序时会产生不正确的结果。 我们通过一个*比值函数*来修正此问题: ```js var numbers = [4, 2, 5, 1, 3]; numbers.sort(function(a, b) { return a - b; }); console.log(numbers); // expected output: [1, 2, 3, 4, 5] ``` 升序排序: ```js var points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return a - b}); // 现在 points[0] 包含最低值 // 而 points[points.length-1] 包含最高值 ``` 降序排序: ```js var points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return b - a}); // 现在 points[0] 包含最高值 // 而 points[points.length-1] 包含最低值 ``` ### 比值函数 比较函数的目的是定义另一种排序顺序。 比较函数应该返回一个负,零或正值,这取决于参数: ```js function compare(a, b) { if (a is less than b by some ordering criterion) { return -1; } if (a is greater than b by the ordering criterion) { return 1; } // a must be equal to b return 0; } ``` 当 sort() 函数比较两个值时,会将值发送到比较函数,并根据所返回的值(负、零或正值)对这些值进行排序。 ```js var items = [ { name: 'Edward', value: 21 }, { name: 'Sharpe', value: 37 }, { name: 'And', value: 45 }, { name: 'The', value: -12 }, { name: 'Magnetic', value: 13 }, { name: 'Zeros', value: 37 } ]; // sort by value items.sort(function (a, b) { return a.value - b.value; }); // sort by name items.sort(function(a, b) { var nameA = a.name.toUpperCase(); // ignore upper and lowercase var nameB = b.name.toUpperCase(); // ignore upper and lowercase if (nameA < nameB) { return -1; } if (nameA > nameB) { return 1; } // names must be equal return 0; }); ``` ### 反转数组 reverse() 方法反转数组中的元素。 ```js var array = ['one', 'two', 'three']; console.log('array: ', array); // expected output: ['one', 'two', 'three'] var reversed = array.reverse(); console.log('reversed: ', reversed); // expected output: ['three', 'two', 'one'] /* Careful: reverse is destructive. It also changes the original array */ console.log('array: ', array); // expected output: ['three', 'two', 'one'] ``` ### 以随机顺序排序数组 ```js var points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return 0.5 - Math.random()}); ``` ## 数组迭代 ### Array.forEach() forEach() 方法为每个数组元素调用一次函数(回调函数): ```js var array1 = ['a', 'b', 'c']; array1.forEach(function(element) { console.log(element); }); // expected output: "a" // expected output: "b" // expected output: "c" ``` > 注:该函数接受 3 个参数:项目值、项目索引、数组本身 ### Array.map() map() 方法通过对每个数组元素执行函数来创建新数组。 map() 方法不会对没有值的数组元素执行函数。 map() 方法不会更改原始数组。 ```js var array = [1, 4, 9, 16]; // pass a function to map const map = array.map(x => x * 2); console.log(map); // expected output: Array [2, 8, 18, 32] ``` > 注:该函数有 3 个参数:项目值、项目索引、数组本身 ### Array.filter() filter() 方法创建一个包含通过测试的数组元素的新数组: 这个例子用值大于 18 的元素创建一个新数组: ### 实例 ```js var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present']; const result = words.filter(word => word.length > 6); console.log(result); // expected output: Array ["exuberant", "destruction", "present"] ``` > 注:此函数接受 3 个参数:项目值、项目索引、数组本身 ### Array.reduce() reduce() 方法在每个数组元素上运行函数,以生成(减少它)单个值。 reduce() 方法在数组中从左到右工作。 reduce() 方法不会减少原始数组。 reduce() 方法能够接受一个初始值。 ```js const array = [1, 2, 3, 4]; // 1 + 2 + 3 + 4 console.log(array.reduce((accumulator, currentValue) => accumulator + currentValue)); // expected output: 10 console.log(array.reduce((accumulator, currentValue, currentIndex, array) => { return accumulator + currentValue; }, 10)); // expected output: 20 ``` > 请注意此函数接受 4 个参数:总数(初始值/先前返回的值)、项目值、项目索引、数组本身 ### Array.reduceRight() reduceRight() 方法在每个数组元素上运行函数,以生成(减少它)单个值。 reduceRight() 方法在数组中从左到右工作。另请参见 reduce()。 reduceRight() 方法不会减少原始数组。 ```js const array = [[0, 1], [2, 3], [4, 5]]; console.log(array.reduceRight( (accumulator, currentValue) => accumulator.concat(currentValue) )); // expected output: Array [4, 5, 2, 3, 0, 1] ``` > 请注意此函数接受 4 个参数:总数(初始值/先前返回的值)、项目值、项目索引、数组本身 ### Array.every() every() 方法检查所有数组值是否通过测试。 ```js var array = [1, 30, 39, 29, 10, 13]; console.log(array.every(currentValue => { return currentValue < 40; })); // expected output: true ``` > 请注意此函数接受 3 个参数:项目值、项目索引、数组本身 ### Array.some() some() 方法检查某些数组值是否通过了测试。 ```js var array = [1, 2, 3, 4, 5]; console.log(array.some(element => { // checks whether an element is even return element % 2 === 0; })); // expected output: true ``` > 请注意此函数接受 3 个参数:项目值、项目索引 ### Array.indexOf() indexOf() 方法在数组中搜索元素值并返回其位置。 ``` array.indexOf(item, start) ``` | *item* | 必需。要检索的项目。 | | ------- | ------------------------------------------------------------ | | *start* | 可选。从哪里开始搜索。负值将从结尾开始的给定位置开始,并搜索到结尾。 | 如果未找到项目,Array.indexOf() 返回 -1。 如果项目多次出现,则返回第一次出现的位置。 ```js var array = [2, 9, 9]; console.log(array.indexOf(2)); // expected output: 0 console.log(array.indexOf(7)); // expected output: -1 console.log(array.indexOf(9, 2)); // expected output: 2 console.log(array.indexOf(2, -1)); // expected output: -1 console.log(array.indexOf(2, -3)); // expected output: 0 ``` ### Array.lastIndexOf() Array.lastIndexOf() 与 Array.indexOf() 类似,但是从数组结尾开始搜索。 ```js var numbers = [2, 5, 9, 2]; console.log(numbers.lastIndexOf(2)); // expected output: 3 console.log(numbers.lastIndexOf(7)); // expected output: -1 console.log(numbers.lastIndexOf(2, 3)); // expected output: 3 console.log(numbers.lastIndexOf(2, 2)); // expected output: 0 console.log(numbers.lastIndexOf(2, -2)); // expected output: 0 console.log(numbers.lastIndexOf(2, -1)); // expected output: 3 ``` ### Array.find() find() 方法返回通过测试函数的第一个数组元素的值。 ```js var array = [5, 12, 8, 130, 44]; console.log(array.find(element => { return element > 10; })); // expected output: 12 ``` > 请注意此函数接受 3 个参数:项目值、项目索引、数组本身 ### Array.findIndex() findIndex() 方法返回通过测试函数的第一个数组元素的索引。 ```js var array1 = [5, 12, 8, 130, 44]; console.log(array1.findIndex(element => { return element > 13; })); // expected output: 3 ``` > 请注意此函数接受 3 个参数:项目值、项目索引、数组本身 ## Math对象 Math对象是JavaScript的内置对象,提供一系列数学常数和数学方法。Math对象只提供了静态的属性和方法,所以使用时不用实例化。 ### round 用于四舍五入。 ```js console.log(Math.round(0.1)); // except output: 0 console.log(Math.round(0.5)); // except output: 1 ``` ### abs 绝对值。 ```js console.log(Math.abs(1)); // except output: 1 console.log(Math.abs(-1)); // except output: 1 ``` ### max & min max方法返回最大的参数,min方法返回最小的参数。 ```js console.log(Math.max(2, -1, 5)); // except output: 5 console.log(Math.min(2, -1, 5)); // except output: -1 ``` ### floor & ceil `floor`方法返回小于参数值的最大整数。 ```js console.log(Math.floor(3.2)); // except output: 3 console.log(Math.floor(-3.2)); // except output: -4 ``` `ceil`方法返回大于参数值的最小整数。 ```js console.log(Math.ceil(3.2)); // except output: 4 console.log(Math.ceil(-3.2)); // except output: -3 ``` ### pow & sqrt pow方法返回以第一个参数为底数、第二个参数为幂的指数值。 ```js console.log(Math.pow(2, 2)); // except output: 4 console.log(Math.pow(2, 3)); // except output: 8 ``` sqrt方法返回参数值的平方根。如果参数是一个负值,则返回NaN。 ```js console.log(Math.sqrt(4)); // except output: 2 console.log(Math.sqrt(-4)); // except output: NaN ``` ### log & exp log方法返回以e为底的自然对数值。 ```jsx console.log(Math.log(Math.E)); // except output: 1 console.log(Math.log(10)); // except output: 2.302585092994046 ``` exp方法返回常数e的参数次方。 ```js console.log(Math.exp(1)); // except output: 2.718281828459045 console.log(Math.exp(3)); // except output: 20.085536923187668 ``` ## random 该方法返回01之间的一个伪随机数,可能等于0,但是一定小于1。 ```js console.log(Math.random()); // except output: 0.7151307314634323 ``` 返回给定范围的随机数。 ```js function getRandomArbitrary(min, max) { return Math.random() * (max - min) + min; } ``` ## 三角函数 sin方法返回参数的正弦,cos方法返回参数的余弦,tan方法返回参数的正切。 ```js console.log(Math.sin(0)); // except output: 0 console.log(Math.cos(0)); // except output: 1 console.log(Math.tan(0)); // except output: 0 ``` asin方法返回参数的反正弦,acos方法返回参数的反余弦,atan方法返回参数的反正切。这三个方法的返回值都是弧度值。 ```js console.log(Math.asin(1)); // except output: 1.5707963267948966 console.log(Math.acos(1)); // except output 0 console.log(Math.atan(1)); // except output 0.7853981633974483 ```