Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step

Home Page:https://juejin.cn/column/7244788137410560055

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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()

//
commented

// 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: []

  1. 数组的length属性
var array = [1, 2, 3];
array.length = 0;

2.splice方法

var array = [1, 2, 3];
array.splice(0,array.length);
  1. 新建一个新的空数组覆盖原来的
var array = [1, 2, 3];
array = [];
  1. shift
var array = [1, 2, 3];
while(array.length > 0) {
    array.shift();
}
  1. pop
var array = [1, 2, 3];
while(array.length > 0) {
    array.pop();
}
  1. slice
var array = [1, 2, 3];
array = array.slice(array.length);
  1. filter
var array = [1, 2, 3];
// 7.1
array = array.filter(() => false);
// 7.2
array = array.filter(item => item !== undefined);
  1. fill
var array = [1, 2, 3];
array.fill(undefined);