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

So with my code, the question which I'm trying to answer in Javascript is to reset the items in an

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]

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744303611a4567621.html

相关推荐

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

    So with my code, the question which I'm trying to answer in Javascript is to reset the items in an

    8天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信