1

On this answer, How do I empty an array in JavaScript? it's suggest to set the Array length value to 0, so if A = [0,0,0,0] then A.length = 0 should make it A = [] But I can't achieve that with my code,

I feel like I am literally doing it right but, javascript is printing the wrong variable

my code is this:

client.fetchCart(localStorage.getItem('lastCartId')).then(function(remoteCart) {
                console.log(cart);
                cart.lineItems.length = 0 ;
                console.log(cart.lineItems.length);
                console.log(cart.lineItems);
                client.updateCart(cart);
            });

The cart is logged before the setting an array length to 0, and then logged again after, but in my debugging both of the logged carts have the same lineItems.length. Which means setting it to 0 with cart.lineItems.length = 0 ; hasn't worked :(

any suggestions?

Community
  • 1
  • 1
lopu
  • 121
  • 1
  • 1
  • 10
  • 2
    Well I see more than 1 solution on the answer site – B001ᛦ Jul 20 '16 at 14:36
  • a = [] is as far as I know the best way to do it. – Dellirium Jul 20 '16 at 14:38
  • just for fun: `cart.items = cart.items.slice(cart.items.length)`. But @Dellirium solution seems better... – TGrif Jul 20 '16 at 18:21
  • "Which means setting it to 0 with cart.lineItems.length = 0 ; hasn't worked" — You've misidentified the problem. The Console you are using is lazy about evaluating objects, so even though you log **before** you modify the array, the displayed value shows the content of the array **after** you modify it. Logging with `console.log(JSON.stringify(cart.lineItems))` would show the data at the right time. – Quentin Aug 01 '19 at 08:56

3 Answers3

5

A = [1, 2, 3]
console.log(A);
A.length = 0;
console.log(A);

It clearly works.

Andrey
  • 59,039
  • 12
  • 119
  • 163
0

here is a lil script for u to try and run successfully :)

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<script type="text/javascript">

    function arr()
    {
        var a=[1,2,3]
        alert(a);
        a=[];
        alert(a);
    }

</script>
<body>
<button onclick="arr()">CLick</button>
</body>
</html>

However there is another in-built function u can try.

which is as per my example a.pop() in a loop till all elements in the array have been removed. For this it is essential to run a loop to iterate over all elements in the array

shruti iyyer
  • 260
  • 2
  • 11
-2
Here is the Better Way of removing all the Element from an Array and also withOut using for Loop,

`    var ary = [12, 4, 15, 18, 19, 21];
     Array.prototype.removeElements = function removeElements(){
         var that = this;
         while(that.length){
              that.shift();
         }
         return that;
     };
     console.log(ary.removeElements());`
bvmCoder
  • 1,131
  • 9
  • 8