0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[JavaScript][Instance Methods] sliceメソッドとは (配列、文字列→範囲抽出)

Posted at

概要

slice()Array インスタンス および String インスタンス のメソッドで、指定した範囲の要素や文字列を切り出して新しい配列や文字列として返します。元の配列や文字列は変更されません。

つまり、

  • 配列で使う場合 → 「部分配列の取得」
  • 文字列で使う場合 → 「部分文字列の取得」
    のためのインスタンスメソッドです。

目次

基本構文

JavaScript
// 配列の部分取得
const arr = [1, 2, 3, 4, 5];
const partArr = arr.slice(1, 4); // インデックス1~3を切り出し

console.log(partArr);
// 出力結果 [2, 3, 4]

// 文字列の部分取得
const str = "hello world";
const partStr = str.slice(0, 5); // 0~4文字目を切り出し

console.log(partStr);
// 出力結果 "hello"

配列と文字列での使用例

配列での slice

JavaScript
const fruits = ["apple", "banana", "orange", "grape"];
const someFruits = fruits.slice(1, 3);

console.log(someFruits);
// 出力結果 ["banana", "orange"]
  • 対象: 配列
  • 戻り値: 指定範囲の新しい配列
  • 用途: 配列の一部を抽出、元配列は変更されない

文字列での slice

JavaScript
const sentence = "I love JavaScript";
const word = sentence.slice(7, 17);

console.log(word);
// 出力結果 "JavaScript"
  • 対象: 文字列
  • 戻り値: 指定範囲の新しい文字列
  • 用途: 部分文字列の抽出、元文字列は変更されない

比較結果

メソッド 対象 役割 戻り値
slice 配列 指定範囲の要素を抽出 配列
slice 文字列 指定範囲の文字を抽出 文字列

活用例

1. 配列の最後の要素だけ取得

JavaScript
const arr = [10, 20, 30, 40];
const lastElement = arr.slice(-1);

console.log(lastElement);
// 出力結果 [40]

2. 文字列の最後の4文字を取得(マスキング用途)

JavaScript
const cc = "1234567890123456";
const last4 = cc.slice(-4);

console.log(last4);
// 出力結果 "3456"

3. 配列の一部をコピー

JavaScript
const numbers = [1, 2, 3, 4, 5];
const copy = numbers.slice(0, 3);

console.log(copy);
// 出力結果 [1, 2, 3]

参考リンク

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?