示例 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时,数组的所有元素都被删除。