-
forEach
for doing a thing with or to every entry in an array; -
filter
for producing a new array containing only qualifying entries; -
map
for making a one-to-one new array by transforming an existing array; -
some
to check whether at least one element in an array fits some description; -
every
to check whether all entries in an array match a description; -
find
to look for a value in an array
Usages | String & Array | |
---|---|---|
String | charCodeAt() split() subString() subStr() trim() |
indexOf() slice() includes() concat() |
Array | map() reduce() filter() push() +pop() +shift() +unshift() join() sort() fill() remove duplicates |
|
Object | keys() +deep copy |
|
Convert | split() String -> Array join() Arrary -> String toString() Number -> String parseInt() String -> Number charCodeAt() String -> ASCII fromCharCode() ASCII -> String Array.from() Object -> Array |
|
判断number | isNaN() |
map()
创建一个新数组,其结果是该数组中每一个元素是调用一次提供的函数后的返回值。 map() 不会修改调用它的原数组本身。
因为map
生成一个新数组,当你不打算使用返回的新数组却使用map
是违背设计初衷的,请用 forEach 或者 for-of 替代。你不该使用map
: A)你不打算使用返回的新数组,或/且 B) 你没有从回调函数中返回值。
map()
方法不能生成一个不同长度的新数组,原数组有多长,返回的新数组就有多长。当返回值不确定时,就会返回undefine
。
语法:
var new_array = arr.map(function callback(currentValue[, index[, array]]) {
// Return element for new_array
}[, thisArg])
在callback()中:
-
currentValue
callback 数组中正在处理的当前元素。 -
index
可选
callback 数组中正在处理的当前元素的索引。 -
array
可选
map 方法调用的数组。
举例:
var numbers = [1, 2, 3, 4];
var filteredNumbers = numbers.map(function(num, index) {
if(index < 3) {
return num;
}
});
//index goes from 0,so the filterNumbers are 1,2,3 and undefined.
// filteredNumbers is [1, 2, 3, undefined]
// numbers is still [1, 2, 3, 4]
建议配套使用 filter,移除不需要的元素。(在使用 map 前或者后都可以,或者只用 filter (如果可以)。
callback的第三个参数arr不常使用。
const array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1.map((x, index, array) => {
return array[index] + 1;
}
);
console.log(map1);
// Array [2, 5, 10, 17]
Object.keys
返回一个所有元素为字符串的数组,其元素来自于从给定的object上面可直接枚举的属性。这些属性的顺序与手动遍历该对象属性时的一致。
例子:
// simple array
var arr = ['a', 'b', 'c'];
console.log(Object.keys(arr)); // console: ['0', '1', '2']
// array like object
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']
// array like object with random key ordering
var anObj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.keys(anObj)); // console: ['2', '7', '100']
reduce() 方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值.
reducer 函数接收4个参数:
1). Accumulator (acc) (累计器)
2). Current Value (cur) (当前值)
3). Current Index (idx) (当前索引) 可选
4). Source Array (src) (源数组) 可选
initialValue 可选
您的 reducer 函数的返回值分配给累计器,该返回值在数组的每个迭代中被记住,并最后成为最终的单个结果值。
arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
不使用initialValue时 reduce()
的运行顺序:
[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array){
return accumulator + currentValue;
});
当存在initialValue时,currentValue从数组第一个元素开始遍历。
例子:将二维数组转化成一维数组
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
function(a, b) {
return a.concat(b);
},
[]
);
// flattened is [0, 1, 2, 3, 4, 5]
filter() 方法创建并返回一个新数组, 其包含通过所提供函数实现的测试的所有元素。
语法:var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])
参数:
callback
用来测试数组的每个元素的函数。返回 true 表示该元素通过测试,保留该元素,false 则不保留。它接受以下三个参数:
1). element
数组中当前正在处理的元素。
2). index 可选
正在处理的元素在数组中的索引。
3). array 可选
调用了 filter 的数组本身。
thisArg 可选
执行 callback 时,用于 this 的值。
例子1: 在数组中搜索🤓
var fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
/**
* Array filters items based on search criteria (query)
*/
function filterItems(query) {
return fruits.filter(function(el) {
return el.toLowerCase().indexOf(query.toLowerCase()) > -1;
})
}
console.log(filterItems('ap')); // ['apple', 'grapes']
console.log(filterItems('an')); // ['banana', 'mango', 'orange']
例子2 -- 筛选较小的值👍
function isBigEnough(element) {
return element >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]
-
String.prototype.indexOf()
语法:str.indexOf(searchValue [, fromIndex])
Array.prototype.indexOf()
返回给定值在数组中第一次出现的index, 如果没有则返回 -1
语法: arr.indexOf(searchElement[, fromIndex])
参数:
searchElement:
fromIndex (optional): 设置搜索起始位置。默认值为0。
1. 如果FI >= arr.length, 数组将不会被搜索, 函数返回 -1。
2. FI < 0, 即从数组最后一位往前数, 但是数组的遍历顺序任然为正序。
例子:
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));
// expected output: 1
// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4
console.log(beasts.indexOf('giraffe'));
// expected output: -1
concat()
方法用于合并两个或多个数组。此方法将不改变原数组,会创建并返回一个新数组。
语法: const new_array = old_array.concat([value1[, value2[, ...[, valueN]]]])
😜例子 -- 合并三个数组:
const num1 = [1, 2, 3];
const num2 = [4, 5, 6];
const num3 = [7, 8, 9];
const numbers = num1.concat(num2, num3);
console.log(numbers);
// results in [1, 2, 3, 4, 5, 6, 7, 8, 9]
🤯例子 -- 合并数值与数组:
const letters = ['a', 'b', 'c'];
const alphaNumeric = letters.concat(1, [2, 3]);
console.log(alphaNumeric);
// results in ['a', 'b', 'c', 1, 2, 3]
join()
方法接受一个数组,创建并返回一个由给定分隔符连接到string
语法:arr.join([separator])
例子:
var a = ['Wind', 'Water', 'Fire'];
a.join(); // 'Wind,Water,Fire'
a.join(', '); // 'Wind, Water, Fire'
a.join(' + '); // 'Wind + Water + Fire'
a.join(''); // 'WindWaterFire'
-
split()
split()
方法用于分割string, 返回一个新数组, 并不会改变原字符串。
语法:string.split(separator, limit)
参数:
1). separator Optional
:
Specifies the character, or the regular expression, to use for splitting the string. If omitted, the entire string will be returned (an array with only one item)
2)limit
:
Optional. An integer that specifies the number of splits, items after the split limit will not be included in the array
例子:
const str = 'The quick brown fox jumps over the lazy dog.';
const words = str.split(' ');
console.log(words);
// ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog."]
const chars = str.split('');
console.log(chars);
// ["T", "h", "e", " ", "q", "u", "i", "c", "k", " ", "b", "r", "o", "w", "n", " ", "f", "o", "x", " ", "j", "u", "m", "p", "s", " ", "o", "v", "e", "r", " ", "t", "h", "e", " ", "l", "a", "z", "y", " ", "d", "o", "g", "."]
const strCopy = str.split();
console.log(strCopy);
// ["The quick brown fox jumps over the lazy dog."]
push()
方法将一个或多个元素添加到数组的末尾,并返回该数组的新长度。
语法:arr.push(element1, ..., elementN)
例子:
const animals = ['pigs', 'goats', 'sheep'];
const count = animals.push('cows');
console.log(count);
// expected output: 4
console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows"]
animals.push('chickens', 'cats', 'dogs');
console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]
-
isNaN()
isNaN()
方法接受一个待测试的数值,如果该值为NaN
, 返回true
。如果为纯数字则返回false
.
语法:isNaN(value)
例子 -- values in different cases:
isNaN(NaN); // true
isNaN(undefined); // true
isNaN({}); // true
isNaN(true); // false
isNaN(null); // false
isNaN(37); // false
// strings
isNaN('37'); // false: "37" is converted to the number 37 which is not NaN
isNaN('37.37'); // false: "37.37" is converted to the number 37.37 which is not NaN
isNaN("37,5"); // true
isNaN('123ABC'); // true: parseInt("123ABC") is 123 but Number("123ABC") is NaN
isNaN(''); // false: the empty string is converted to 0 which is not NaN
isNaN(' '); // false: a string with spaces is converted to 0 which is not NaN
// dates
isNaN(new Date()); // false
isNaN(new Date().toString()); // true
// This is a false positive and the reason why isNaN is not entirely reliable
isNaN('blabla'); // true: "blabla" is converted to a number.
// Parsing this as a number fails and returns NaN
parseInt()
接受一个String, 并返回一个指定基数(radix)的integer.
语法:parseInt(string [, radix])
参数:
radix 为一个 2-36之间的integer,它是可选参数。
- 在radix被省略的情况下:
If the string begins with "0x", the radix is 16 (hexadecimal)
If the string begins with "0", the radix is 8 (octal). This feature is deprecated
If the string begins with any other value, the radix is 10 (decimal)
toString()
方法用于将数字转化成String
语法: num.toString(base)
参数:
base是一个范围在 2-36 之间的可选数字。
例子:
<script type="text/javascript">
var num=12;
document.write("Output : " + num.toString(2));
</script>
//Output:1100
<script type="text/javascript">
var num=213;
document.write("Output : " + num.toString());
</script>
//Output :213
The charCodeAt()
method returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index.
语法: str.charCodeAt(index)
const sentence = 'The quick brown fox jumps over the lazy dog.';
const index = 4;
console.log(`The character code ${sentence.charCodeAt(index)} is equal to ${sentence.charAt(index)}`);
// expected output: "The character code 113 is equal to q"
tips: 可以用于将string类型的数字,转化为int(需要减去48)。
"123".charCodeAt(2) - 48
即可以得到数字3.
将UTF-16码转化成对应的String
语法:String.fromCharCode(num1[, ...[, numN]])
console.log(String.fromCharCode(3 + 48));
// output: "3"
-
sort()
sort()
方法升序排列数组后返回新数组。
语法: arr.sort([compareFunction])
如果没有写入 compare
方法,则将element转化为string,再排序。
如果希望按照数值大小排序, 则传入compare function
.
例子:
const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]
array1.sort((a, b) => a-b);
console.log(array1);
// expected output: Array [1, 4, 21, 30,100000]
-
Array.prototype.includes()
判断某个元素是否存在数组中。存在返回true
, 不存在返回false
.
语法:arr.includes(valueToFind[, fromIndex])
String.prototype.includes()
判断某个字符串是否包含于另一个字符串中。存在返回true
, 不存在返回false
.
语法: str.includes(searchString[, position])
ps: 搜索包含position index
-
slice()
Array 和 String 都可以使用此方法。slice()
returns a shallow copy of a portion of an array or a String into a new Object or String. The portion from start to end(end not included).包头不包尾。
arr.slice([start[, end]])
slice()
方法与substring()
方法和subStr()
方法相似,这里是详细说明。
-
fill()
fill()
方法将Array中的所有元素改变为静态值。此方法将直接改变原数组。
arr.fill(value[, start[, end]])
const array1 = [1, 2, 3, 4];
// fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// expected output: [1, 2, 0, 0]
// fill with 5 from position 1
console.log(array1.fill(5, 1));
// expected output: [1, 5, 5, 5]
console.log(array1.fill(6));
// expected output: [6, 6, 6, 6]
-
trim()
Thetrim()
method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).
str.trim()