JavaScript怎么清空数组
Sunny-117 opened this issue · comments
JavaScript怎么清空数组
let sheldon = ['c','o','o','p','e','r']
//methods 1
sheldon = []
// methods 2
sheldon.length = 0
// methods 3
sheldon.splice(0, sheldon.length)
// methods 4
while(sheldon.length > 0) sheldon.pop()
//
// methods 1
let myArray = [1, 2, 3, 4, 5];
myArray.length = 0;
console.log(myArray); // Output: []
// methods 2
let myArray = [1, 2, 3, 4, 5];
myArray.splice(0, myArray.length);
console.log(myArray); // Output: []
// methods 3
arry = [1, 2, 3, 4];
arry = [];
console.log(arry); //Output: []
// method 4
arry = [1, 2, 3, 4];
while (arry.length > 0) {
arry.pop();
}
console.log(arry);
//Output: []
// mehtod 5
arry = [1, 2, 3, 4];
while (arry.length > 0) {
arry.shift();
}
console.log(arry);
//Output: []
- 数组的length属性
var array = [1, 2, 3];
array.length = 0;
2.splice方法
var array = [1, 2, 3];
array.splice(0,array.length);
- 新建一个新的空数组覆盖原来的
var array = [1, 2, 3];
array = [];
- shift
var array = [1, 2, 3];
while(array.length > 0) {
array.shift();
}
- pop
var array = [1, 2, 3];
while(array.length > 0) {
array.pop();
}
- slice
var array = [1, 2, 3];
array = array.slice(array.length);
- filter
var array = [1, 2, 3];
// 7.1
array = array.filter(() => false);
// 7.2
array = array.filter(item => item !== undefined);
- fill
var array = [1, 2, 3];
array.fill(undefined);