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() 創(chuàng)建一個(gè)新數(shù)組眶掌,其結(jié)果是該數(shù)組中每一個(gè)元素是調(diào)用一次提供的函數(shù)后的返回值骂倘。 map() 不會(huì)修改調(diào)用它的原數(shù)組本身走趋。

因?yàn)?code>map生成一個(gè)新數(shù)組熬北,當(dāng)你不打算使用返回的新數(shù)組卻使用map是違背設(shè)計(jì)初衷的败潦,請(qǐng)用 forEach 或者 for-of 替代啃擦。你不該使用map: A)你不打算使用返回的新數(shù)組格带,或/且 B) 你沒(méi)有從回調(diào)函數(shù)中返回值撤缴。

map() 方法不能生成一個(gè)不同長(zhǎng)度的新數(shù)組,原數(shù)組有多長(zhǎng)叽唱,返回的新數(shù)組就有多長(zhǎng)屈呕。當(dāng)返回值不確定時(shí),就會(huì)返回undefine棺亭。

語(yǔ)法:

var new_array = arr.map(function callback(currentValue[, index[, array]]) {
 // Return element for new_array 
}[, thisArg])

在callback()中:

  • currentValue
    callback 數(shù)組中正在處理的當(dāng)前元素凉袱。
  • index可選
    callback 數(shù)組中正在處理的當(dāng)前元素的索引。
  • array可選
    map 方法調(diào)用的數(shù)組侦铜。

舉例:

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的第三個(gè)參數(shù)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 返回一個(gè)所有元素為字符串的數(shù)組贡未,其元素來(lái)自于從給定的object上面可直接枚舉的屬性种樱。這些屬性的順序與手動(dòng)遍歷該對(duì)象屬性時(shí)的一致。

例子:

// 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() 方法對(duì)數(shù)組中的每個(gè)元素執(zhí)行一個(gè)由您提供的reducer函數(shù)(升序執(zhí)行)俊卤,將其結(jié)果匯總為單個(gè)返回值.

reducer 函數(shù)接收4個(gè)參數(shù):
?1). Accumulator (acc) (累計(jì)器)
?2). Current Value (cur) (當(dāng)前值)
?3). Current Index (idx) (當(dāng)前索引) 可選
?4). Source Array (src) (源數(shù)組) 可選
initialValue 可選

您的 reducer 函數(shù)的返回值分配給累計(jì)器嫩挤,該返回值在數(shù)組的每個(gè)迭代中被記住,并最后成為最終的單個(gè)結(jié)果值消恍。

arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])

不使用initialValue時(shí) reduce() 的運(yùn)行順序:

[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array){
  return accumulator + currentValue;
});

當(dāng)存在initialValue時(shí)岂昭,currentValue從數(shù)組第一個(gè)元素開始遍歷。

例子:將二維數(shù)組轉(zhuǎn)化成一維數(shù)組

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() 方法創(chuàng)建并返回一個(gè)新數(shù)組, 其包含通過(guò)所提供函數(shù)實(shí)現(xiàn)的測(cè)試的所有元素狠怨。
語(yǔ)法:var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])

參數(shù):
callback
用來(lái)測(cè)試數(shù)組的每個(gè)元素的函數(shù)约啊。返回 true 表示該元素通過(guò)測(cè)試,保留該元素佣赖,false 則不保留恰矩。它接受以下三個(gè)參數(shù):
?1). element
?數(shù)組中當(dāng)前正在處理的元素。
?2). index 可選
?正在處理的元素在數(shù)組中的索引憎蛤。
?3). array 可選
?調(diào)用了 filter 的數(shù)組本身外傅。
thisArg 可選
執(zhí)行 callback 時(shí),用于 this 的值。

例子1: 在數(shù)組中搜索??

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()
    語(yǔ)法:str.indexOf(searchValue [, fromIndex])

Array.prototype.indexOf()
返回給定值在數(shù)組中第一次出現(xiàn)的index萎胰, 如果沒(méi)有則返回 -1
語(yǔ)法: arr.indexOf(searchElement[, fromIndex])

參數(shù):
?searchElement:
?fromIndex (optional): 設(shè)置搜索起始位置碾盟。默認(rèn)值為0。
?? 1. 如果FI >= arr.length, 數(shù)組將不會(huì)被搜索奥洼, 函數(shù)返回 -1巷疼。
?? 2. FI < 0, 即從數(shù)組最后一位往前數(shù), 但是數(shù)組的遍歷順序任然為正序灵奖。

例子:

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()方法用于合并兩個(gè)或多個(gè)數(shù)組嚼沿。此方法將不改變?cè)瓟?shù)組,會(huì)創(chuàng)建并返回一個(gè)新數(shù)組瓷患。
語(yǔ)法: const new_array = old_array.concat([value1[, value2[, ...[, valueN]]]])

??例子 -- 合并三個(gè)數(shù)組:

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]

??例子 -- 合并數(shù)值與數(shù)組:

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() 方法接受一個(gè)數(shù)組骡尽,創(chuàng)建并返回一個(gè)由給定分隔符連接到string
語(yǔ)法: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, 返回一個(gè)新數(shù)組擅编, 并不會(huì)改變?cè)址?br> 語(yǔ)法:string.split(separator, limit)

參數(shù):
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()方法將一個(gè)或多個(gè)元素添加到數(shù)組的末尾攀细,并返回該數(shù)組的新長(zhǎng)度。
語(yǔ)法: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() 方法接受一個(gè)待測(cè)試的數(shù)值爱态,如果該值為NaN谭贪, 返回true。如果為純數(shù)字則返回false.
    語(yǔ)法: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() 接受一個(gè)String锦担, 并返回一個(gè)指定基數(shù)(radix)的integer.
語(yǔ)法:parseInt(string [, radix])

參數(shù):
? radix 為一個(gè) 2-36之間的integer俭识,它是可選參數(shù)。

  • ?在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() 方法用于將數(shù)字轉(zhuǎn)化成String
語(yǔ)法: num.toString(base)

參數(shù):
? base是一個(gè)范圍在 2-36 之間的可選數(shù)字洞渔。

例子:

<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.
語(yǔ)法: 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類型的數(shù)字套媚,轉(zhuǎn)化為int(需要減去48)。
"123".charCodeAt(2) - 48 即可以得到數(shù)字3.



  1. String.fromCharCode()

將UTF-16碼轉(zhuǎn)化成對(duì)應(yīng)的String
語(yǔ)法:String.fromCharCode(num1[, ...[, numN]])

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



  1. sort()
    sort() 方法升序排列數(shù)組后返回新數(shù)組磁椒。

語(yǔ)法: arr.sort([compareFunction])
如果沒(méi)有寫入 compare 方法堤瘤,則將element轉(zhuǎn)化為string,再排序浆熔。
如果希望按照數(shù)值大小排序本辐, 則傳入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()
    判斷某個(gè)元素是否存在數(shù)組中。存在返回true, 不存在返回false.

語(yǔ)法:arr.includes(valueToFind[, fromIndex])

String.prototype.includes()
判斷某個(gè)字符串是否包含于另一個(gè)字符串中蘸拔。存在返回true, 不存在返回false.

語(yǔ)法: 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()方法相似调窍,這里是詳細(xì)說(shuō)明。



  1. fill()
    fill()方法將Array中的所有元素改變?yōu)殪o態(tài)值张遭。此方法將直接改變?cè)瓟?shù)組邓萨。

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子缔恳,更是在濱河造成了極大的恐慌宝剖,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,640評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件歉甚,死亡現(xiàn)場(chǎng)離奇詭異万细,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)纸泄,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,254評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門赖钞,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人聘裁,你說(shuō)我怎么就攤上這事雪营。” “怎么了衡便?”我有些...
    開封第一講書人閱讀 165,011評(píng)論 0 355
  • 文/不壞的土叔 我叫張陵献起,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我镣陕,道長(zhǎng)谴餐,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,755評(píng)論 1 294
  • 正文 為了忘掉前任呆抑,我火速辦了婚禮岂嗓,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘理肺。我一直安慰自己摄闸,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,774評(píng)論 6 392
  • 文/花漫 我一把揭開白布妹萨。 她就那樣靜靜地躺著年枕,像睡著了一般。 火紅的嫁衣襯著肌膚如雪乎完。 梳的紋絲不亂的頭發(fā)上熏兄,一...
    開封第一講書人閱讀 51,610評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音树姨,去河邊找鬼摩桶。 笑死,一個(gè)胖子當(dāng)著我的面吹牛帽揪,可吹牛的內(nèi)容都是我干的硝清。 我是一名探鬼主播,決...
    沈念sama閱讀 40,352評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼转晰,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼芦拿!你這毒婦竟也來(lái)了士飒?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,257評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤蔗崎,失蹤者是張志新(化名)和其女友劉穎酵幕,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體缓苛,經(jīng)...
    沈念sama閱讀 45,717評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡芳撒,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,894評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了未桥。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片笔刹。...
    茶點(diǎn)故事閱讀 40,021評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖钢属,靈堂內(nèi)的尸體忽然破棺而出徘熔,到底是詐尸還是另有隱情,我是刑警寧澤淆党,帶...
    沈念sama閱讀 35,735評(píng)論 5 346
  • 正文 年R本政府宣布酷师,位于F島的核電站,受9級(jí)特大地震影響染乌,放射性物質(zhì)發(fā)生泄漏山孔。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,354評(píng)論 3 330
  • 文/蒙蒙 一荷憋、第九天 我趴在偏房一處隱蔽的房頂上張望台颠。 院中可真熱鬧,春花似錦勒庄、人聲如沸串前。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,936評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)荡碾。三九已至,卻和暖如春局装,著一層夾襖步出監(jiān)牢的瞬間坛吁,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,054評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工铐尚, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留拨脉,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,224評(píng)論 3 371
  • 正文 我出身青樓宣增,卻偏偏與公主長(zhǎng)得像玫膀,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子爹脾,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,974評(píng)論 2 355