What element sees the method has for WeakSet?



  • There's a code:

    let messages = [
      { text: "Hello", from: "John" },
      { text: "How goes?", from: "John1" },
      { text: "See you soon", from: "Alice" }
    ];
    

    let answer = new WeakSet();

    answer.add(messages[0]);
    answer.add(messages[1]);
    answer.add(messages[2]);

    messages.shift()

    alert("0: " + answer.has(messages[0]));
    alert("1: " + answer.has(messages[1]));
    alert("2: " + answer.has(messages[2]));

    Method shift() removes the first element of the mass, in our case { text: "Hello", from: "John" }The screen shall be displayed:

    0: true
    1: true
    2: false

    Why? 0: true?

    If the method shift() is to delete messages[0], the conclusion will be correct:

    0: false
    1: true
    2: true

    If a splice(0) method is used instead of the shift method, the conclusion will be:

    0: true
    1: true
    2: false

    I mean, it's not right either.



  • That's right.

    That's how it works. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

    The body is removed, the rest are moving.

    I mean, after the call.

    messages.shift()
    

    or

    messages.splice(0, 1)
    

    messages The following elements will remain:

    [
      { text: "How goes?", from: "John1" },
      { text: "See you soon", from: "Alice" }
    ];
    

    So you're actually checking on the first and second element and under index 2 is lying. undefined - because there's no element with such an index in the mass.


Log in to reply
 

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2