清空数组中的值
在JavaScript中,可以使用以下方法清空数组中的值:
- 使用
length属性将数组的长度设置为0,这将删除数组中的所有元素:
let arr = [1, 2, 3];
arr.length = 0;
console.log(arr); // Output: []
- 使用
splice()方法删除数组中的所有元素:
let arr = [1, 2, 3];
arr.splice(0, arr.length);
console.log(arr); // Output: []
- 使用循环遍历数组并将每个元素设置为
undefined:
let arr = [1, 2, 3];
for(let i = 0; i < arr.length; i++) {
arr[i] = undefined;
}
console.log(arr); // Output: [undefined, undefined, undefined]
请注意,这种方法不会删除数组中的元素,但是将它们设置为undefined可能会使数组在后续操作中出现问题。
原文地址: https://www.cveoy.top/t/topic/8FQ 著作权归作者所有。请勿转载和采集!