Program JavaScript untuk Mengosongkan Array

0
(0)

Contoh 1: Array Kosong dengan Mengganti Array Baru

// program to empty an array

function emptyArray(arr) {

    // substituting new array
    arr = [];
    
    return arr;
}

const array = [1, 2 ,3];
console.log(array);

// call the function
const result = emptyArray(array);
console.log(result);

Keluaran

[1, 2, 3]
[]

Pada program di atas, nilai Himpunan digantikan oleh array kosong baru.


Contoh 2: Array Kosong Menggunakan splice()

// program to append an object to an array

function emptyArray(arr) {

    // substituting new array
    arr.splice(0, arr.length);
    
    return arr;
}

const array = [1, 2 ,3];
console.log(array);

// call the function
const result = emptyArray(array);
console.log(result);

Keluaran

[1, 2, 3]
[]

Pada program di atas, splice() Metode ini digunakan untuk menghapus semua elemen array.

Dalam splice() metode,

  • Argumen pertama adalah indeks array untuk mulai menghapus item.
  • Argumen kedua adalah jumlah elemen yang ingin Anda hapus dari elemen indeks.

Contoh 3: Array Kosong dengan Mengatur Panjang 0

// program to empty an array

function emptyArray(arr) {

    // setting array length to 0
    arr.length = 0;
    
    return arr;
}

const array = [1, 2 ,3];
console.log(array);

// call the function
const result = emptyArray(array);
console.log(result);

Keluaran

[1, 2, 3]
[]

Dalam program di atas, properti length digunakan untuk mengosongkan array.

Saat mengatur array.length untuk 0, semua elemen array dihapus.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.