Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step
https://juejin.cn/column/7244788137410560055
2.02k stars 235 forks source link

JavaScript怎么清空数组 #89

Open Sunny-117 opened 2 years ago

Nasuke commented 2 years ago
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()

//
ppjiucai commented 1 year ago

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

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

    2.splice方法

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

array.fill*()

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

array.fill(undefined)不可以吧


[ undefined, undefined, undefined ]