JavaScript 中的一些常用方法

  • 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()


  1. map()

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]



  1. Object.keys(obj)

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']



  1. reduce()

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]



  1. filter()

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] 



  1. 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



  1. concat()

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]



  1. join()

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'



  1. 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."]



  1. push()

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"]



  1. 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



  1. parseInt()

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)



  1. toString()

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



  1. String.prototype.charCodeAt()

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.



  1. String.fromCharCode()

将UTF-16码转化成对应的String
语法:String.fromCharCode(num1[, ...[, numN]])

console.log(String.fromCharCode(3 + 48));
// output: "3"



  1. 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]



  1. Array.prototype.includes()
    判断某个元素是否存在数组中。存在返回true, 不存在返回false.

语法:arr.includes(valueToFind[, fromIndex])

String.prototype.includes()
判断某个字符串是否包含于另一个字符串中。存在返回true, 不存在返回false.

语法: str.includes(searchString[, position])

ps: 搜索包含position index



  1. 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()方法相似,这里是详细说明。



  1. 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]


  1. trim()
    The trim() 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()

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,117评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,963评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,897评论 0 240
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,805评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,208评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,535评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,797评论 2 311
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,493评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,215评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,477评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,988评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,325评论 2 252
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,971评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,807评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,544评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,455评论 2 266