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 dobasket = []
(orbasket.length = 0;
)? – gen_Eric Commented Mar 18, 2021 at 19:50
1 Answer
Reset to default 4If 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]