最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to reset to an empty array - Stack Overflow

programmeradmin5浏览0评论

So with my code, the question which I'm trying to answer in Javascript is to reset the items in an array, where it's creating a function named empty, and then reset the items inside an array. So far I have tried out pop array and it lists the whole array out, and then I have tried to write it by using array length.

Here is my code set up for this one:

function empty(){
  for(var basket = basket.length=0;  basket--);
}
console.log('Reset basket:', basket);

So with my code, the question which I'm trying to answer in Javascript is to reset the items in an array, where it's creating a function named empty, and then reset the items inside an array. So far I have tried out pop array and it lists the whole array out, and then I have tried to write it by using array length.

Here is my code set up for this one:

function empty(){
  for(var basket = basket.length=0;  basket--);
}
console.log('Reset basket:', basket);
Share Improve this question asked Mar 18, 2021 at 19:44 atruckenatrucken 111 gold badge1 silver badge3 bronze badges 2
  • um, firstly, basket would be undefined so an error would throw immediately, secondly, the syntax in that forloop makes no sense :{ – The Bomb Squad Commented Mar 18, 2021 at 19:47
  • 1 What are you trying to do to basket? Couldn't you just do basket = [] (or basket.length = 0;)? – gen_Eric Commented Mar 18, 2021 at 19:50
Add a ment  | 

1 Answer 1

Reset to default 4

If you need to replace just the variable basket with an empty array, simply reassign it:

basket = [];

If you need to reset the actual array referenced by the variable, and therefore reset all references to the same array, simply set .length to 0.

basket.length = 0;

Your syntax though is incorrect. As a function, it would look like:

function empty(array) {
  array.length = 0;
}

let arr1 = [1, 2, 3];
let arr2 = arr1; // both variables reference the same array
let arr3 = [...arr1]; // references a different array

empty(arr1);

console.log(arr1); // []
console.log(arr2); // []
console.log(arr3); // [1, 2, 3]

发布评论

评论列表(0)

  1. 暂无评论