Javascript 配列メソッド Ep.3
8138 ワード
こんにちは👋
Array Methods Explain Show のエピソード 3 へようこそ.
いつものように、あなたがここにいるのなら、JavaScript と配列の予備知識が必要だと思います.
このエピソードでは、SLICE という 1 つの方法についてのみ説明します.
スライス は元の配列を変更しません.元の配列から要素のコピーを返します.
スライス メソッドの構文は次のとおりです.
beginIndex (オプション) :
endIndex (オプション) :
抽出された要素を含む新しい配列を返します.
それでは、例を見てみましょう:
指定された開始インデックスを持つサブ配列を返します
指定された開始インデックスと終了インデックスを持つサブ配列を返します
引数なしでサブ配列を返す
開始インデックスが負のサブ配列を返す
負の終了インデックスを持つサブ配列を返す
スライス は元の配列を変更しません.元の配列から要素のコピーを返します.コピーは次のように行われます -
オブジェクトの場合、スライスはオブジェクト参照を新しい配列にコピーします.元の配列と新しい配列の両方が同じオブジェクトを参照します.オブジェクトが変更された場合、その変更は新しい配列と元の配列の両方に表示されます. 文字列、数値、ブール値 (文字列、数値、ブール オブジェクトではない) の場合、スライスは値を新しい配列にコピーします.一方の配列で文字列、数値、またはブール値を変更しても、もう一方の配列には影響しません.
いずれかの配列に新しい要素が追加されても、もう一方の配列は影響を受けません.
Array Methods Explain Show のエピソード 3 へようこそ.
いつものように、あなたがここにいるのなら、JavaScript と配列の予備知識が必要だと思います.
このエピソードでは、SLICE という 1 つの方法についてのみ説明します.
スライス は元の配列を変更しません.元の配列から要素のコピーを返します.
スライス メソッドの構文は次のとおりです.
beginIndex (オプション) :
The starting index from which you want to start the extraction.
If beginIndex > length of array, then empty array is returned.
If start is negative, then it starts from last of array.
endIndex (オプション) :
The ending index at which you want to stop the extraction.
If endIndex > length of array, then whole array is returned. If start is negative, then it starts from last of array.
抽出された要素を含む新しい配列を返します.
それでは、例を見てみましょう:
let colors = ["Red", "Blue", "Yellow", "White", "Black"];
let newColors = colors.slice(2); // return a sub array from index 2
console.log(newColors); // ["Yellow", "White", "Black"]
let colors = ["Red", "Blue", "Yellow", "White", "Black"];
let newColors = colors.slice(2,4); // return a sub array from index 2 to 4
console.log(newColors); // ["Yellow", "White"]
let colors = ["Red", "Blue", "Yellow", "White", "Black"];
let newColors = colors.slice(); // return whole array
console.log(newColors); // ["Red", "Blue", "Yellow", "White", "Black"]
let colors = ["Red", "Blue", "Yellow", "White", "Black"];
let newColors = colors.slice(-2); // return a sub array from index 2 (from last)
console.log(newColors); // ["White", "Black"]
let colors = ["Red", "Blue", "Yellow", "White", "Black"];
let newColors = colors.slice(1, -2); // return a sub array from index 1 to 2 (from last)
console.log(newColors); // ["Blue", "Yellow"]
舞台裏
スライス は元の配列を変更しません.元の配列から要素のコピーを返します.コピーは次のように行われます -
いずれかの配列に新しい要素が追加されても、もう一方の配列は影響を受けません.
Reference
この問題について(Javascript 配列メソッド Ep.3), 我々は、より多くの情報をここで見つけました https://dev.to/theadeshkhanna/javascript-array-methods-ep3-137gテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol