示例 1:通过替换新数组创建空数组
// 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);
输出
[1, 2, 3] []
在上面的程序中,array 的值被替换为一个新的空数组。
示例 2:使用 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);
输出
[1, 2, 3] []
在上面的程序中,使用 splice()
方法删除数组中的所有元素。
在 splice()
方法中,
- 第一个参数是要从哪个数组索引开始删除项。
- 第二个参数是要从索引元素中删除的元素数量。
示例 3:通过设置长度为 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);
输出
[1, 2, 3] []
在上面的程序中,length 属性用于清空数组。
将 array.length
设置为 0 时,数组中的所有元素都会被移除。
另请阅读