JavaScript_javascript スキルにおける配列オブジェクトの組み込みメソッドの紹介

WBOY
リリース: 2016-05-16 17:40:33
オリジナル
974 人が閲覧しました

/**
* この記事は、現在の W3C 標準における配列オブジェクトの組み込みメソッドを単に整理することを目的としています。
* 全文は栄養価が高いものではありませんが、パフォーマンス テストの最後の部分ではいくつかの疑問が生じます。
*/
Mutator メソッド
これらのメソッドは配列自体を直接変更します
pop および Push
Array.pop (); // 配列の最後の要素を削除し、削除された要素を返します。
Array.push(element1, ..., elementN) // 配列の最後に 1 ~ N の要素を挿入し、配列の長さを返します。操作後
このポップとプッシュにより、配列をスタックとしてシミュレートして操作できます。
スタックのデータ構造の特徴は「後入れ先出し」(LIFO、Last In First Out)です。
shift and unshift
Array.shift(); // 配列の最初の要素を削除し、削除された要素を返します
Array.unshift(element1, ..., elementN) ; // 1 ~ N の要素を配列の先頭に挿入し、演算後の配列の長さを返します
キュー演算を実装するにはシフトとシフト解除を使用します。
キューの動作モードはスタックの動作モードとは逆で、「先入れ先出し」(FIFO、先入れ先出し) を使用します。
splice

コードをコピー コードは次のとおりです:

Array.splice(index, howMany[, element1[, ...[, elementN]]]);
Array.splice(index);
インデックス:要素の追加/削除を指定する場所。
howmany: 削除する要素の数を指定します。
elements: 配列に追加する新しい要素を指定します。インデックスが指す添え字から始まります。
スプライス メソッドは、ポップ、プッシュ、シフト、シフト解除を補完するものです。
戻り値は削除された要素です。

reverse

Array. reverse(); // 配列内の要素の順序を反転し、反転した配列を返します


sort

コードをコピーします コードは次のとおりです。
Array.sort([compareFunction]);


If noパラメータはこのメソッドを呼び出すときに使用され、配列内の要素をアルファベット順に並べ替えます。
正確には文字コードの順序に従ってソートされています。
他の基準で並べ替えたい場合は、2 つの値を比較し、2 つの値の相対的な順序を表す数値を返す比較関数を提供する必要があります。比較関数には 2 つのパラメータ a と b が必要で、戻り値は次のとおりです:
•a が b より小さい場合、a は並べ替えられた配列内で b より前に表示され、0 より小さい値を返します。
•a が b と等しい場合、0 を返します。
•aがbより大きい場合、0より大きい値を返します。
----------------------------------------------- --- ----------------------------------

アクセスメソッド
これらのメソッドは、配列自体を変更せずに、対応する結果を返すだけです
concat

Array.concat(value1, value2, ..., valueN); // 2 つ以上の配列をリンクし、結合された配列を返します


ただし、次の例で示すように、注意する必要があることが 1 つあります。


コードをコピーします コードは次のとおりです。
var arr = [1, 2, 3];
arr.concat(4, 5); // return [1, 2, 3, 4, 5]
arr.concat([ 4, 5]); // 戻り値 [1, 2, 3, 4, 5]
arr.concat([4, 5], [6, 7]); 1, 2, 3, 4, 5, 6, 7]
arr.concat(4, [5, [6, 7]]) // 戻り値 [1, 2, 3, 4, 5, [6] , 7]]


join
string = Array.join(separator); 配列内のすべての要素を文字列に入れます。このうち要素は指定された区切り文字で区切られます。
デフォルトの区切り文字はカンマ (,) で、戻り値は結合された文字列です。
[1, 2, 3].join(); // return "1,2,3"Array.join() メソッドは実際には String.splite() の逆の操作です。

スライス

Array.slice(begin[, end]); // 配列内の選択された要素を返します


toString
コードをコピー コードは次のとおりです:


>Array.toString(); // これについてはこれ以上説明しません。すべての JavaScript には toString メソッドが必要です

indexOf および lastIndexOf
*[ECMAScript 5] コードをコピーします
コードは次のとおりです。


Array.indexOf(searchElement[, fromIndex]); //
配列を最初から検索 .lastIndexOf(searchElement[, fromIndex]); // 末尾から検索


searchElement: 検索する値
fromIndex: 開始位置を示すインデックス検索---- -------------------------------------- --------- ------------------------
反復メソッド
forEach *[ECMAScript 5] // 配列を最初から最後まで走査し、配列内の各要素に対して、指定された関数を呼び出します。 パラメータ: コールバック: 配列を走査するときに呼び出される関数thisArg: コールバックを指定します のスコープ さらに、コールバックは 3 つのパラメータを呼び出します:
value: 配列要素
index: 配列インデックス
array: 配列自体



コードをコピー


コードは次のとおりです:

[1, 2].forEach(function(value,index, array) { console.log(値, インデックス, 配列) }); // return // 1 0 [1, 2] // 2 1 [1 , 2]
注: forEach はブレークを通じて配列の走査を中断できません。
解決策: try メソッドを使用して例外をスローし、トラバーサルを終了します。




コードをコピー

コードは次のとおりです:

try { [1,2 ,3] .forEach(function(val) { console.log(val); throw(e) }); } catch(e) { console.log( e);
}



map
*[ECMAScript 5]
Array.map(callback[, thisArg]); // 配列要素を走査し、呼び出します。指定された関数、およびすべての結果を配列として返します
パラメーター:
コールバック: 配列をトラバースするときに呼び出される関数
thisObject: コールバックのスコープを指定します
例:


コードをコピーします


コードは次のとおりです:

[1, 2, 3].map(function(num) { / / return [2, 3, 4] return num 1 filter *[ECMAScript 5]


コードをコピーします

コードは次のとおりです:
Array.filter(callback[, thisObject]); // 配列を走査します。条件を満たす要素 (true を返す) が戻り値の配列に追加されます。

コードをコピー

コードは次のとおりです:


[1, 2, 3].filter(function(num) { // return [1]
return num }); 🎜>すべてといくつか *[ECMAScript 5] コードをコピー

コードは次のとおりです:


Array.every(callback[, thisObject]) // "AND"
Array.some(callback[, thisObject]); // "または"
パラメータ:
callback: 配列を走査するときに呼び出される関数
thisObject: コールバックのスコープを指定します every : すべての要素が関数を呼び出して true を返す場合、結果は true を返し、それ以外の場合は false を返します。 some: すべての要素が関数を呼び出して false を返す場合、結果は false を返し、それ以外の場合は true を返します。 すべての戻り値と一部の戻り値が決定されると、トラバースは直ちに停止します。 例:

コードをコピー

コードは次のとおりです:

[1, 2, 3]. every(function(num) { // return false
return num > 1;
});
[1, 2, 3] . some(function(num) { // return true
return num > 2;
});

reduce and reduceRight *[ECMAScript 5] / / Use the specified method to combine array elements, from low to high (from left to right)
Array.reduceRight(callback[, initialValue]); // Use the specified method to combine array elements, according to Index from high to low (right to left)
Parameters: callback: the function called when traversing the array initialValue: the previousValue passed in when the callback is called for the first time In addition, the callback will call four parameters: previousValue: the cumulative result of the operation so far
currentValue: array element
index: array index
array: the array itself
Example:
[1, 2, 3]. reduce(function(x, y) { // return 106
return x y;
}, 100);
---------- -------------------------------------------------- --------------------

Performance test

Test system: Windows 7
Test browser: Chrome 26.0.1386.0




Copy code

The code is as follows:

var arr = [];
for(var i = 0; i < 999999; i ) { arr.push(i); } forEach




Copy code

The code is as follows:
function forEachTest() {
howTime("forEach", function() {
var num = 0; arr.forEach(function(val, key) { num = val; }); }); howTime("for" , function() { var num = 0;
for(var i = 0, len = arr.length; i < len; i ) {
num = arr[i];
}
});
}


The following are the results of 3 random tests (the specific results are related to the computer configuration, the smaller the result, the better the performance):

time_forEach

time_for
1421.000ms 64.000ms
1641.000ms 63.000ms
1525.000ms 63.000ms

As you can see, Chrome has not specifically optimized forEach. Compared with directly using for loop traversal, the performance is still better. A big gap.
Because forEach is an ECMAScript 5 thing, older browsers do not support it.
However, MDN has provided a backward compatible solution:


time_forEach time_for
1421.000ms  64.000ms 
1641.000ms  63.000ms 
1525.000ms  63.000ms 
Copy the code


The code is as follows:
}


What’s outrageous is that the native forEach Method, in terms of performance, is actually not as good as the forEach constructed by yourself!
Also, what about other iteration methods of other Array objects?
You will basically understand it after looking at this Demo: http://maplejan.sinaapp.com/demo/ArratMethod.html
In addition, I also discovered an interesting situation.
If you run the Demo JavaScript code directly on the console, you will find a big difference in performance!
At this time, the performance of writing directly using a for loop will be even worse.
Regarding this question, I asked it on Zhihu. The question address is: http://www.zhihu.com/question/20837774
関連ラベル:
ソース:php.cn
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
最新の問題
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!