0

I have a question about delete object propery,for examble:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>test</title>
</head>

<body>
  <script type="text/javascript">
    var tmp = {
      x: 1,
      y: 2,
      z: 3
    };
    var tmp1 = {
      x: 1
    };


    for (pro in tmp) {
      console.log("get tmp <<" + pro + ">> property!!");

      if (!tmp1.hasOwnProperty(pro)) {
        console.log("we will delete <<" + pro + ">> property");
        delete tmp.pro; // or delete tmp[pro];
      }
    }

    console.log("--------------");
    for (p in tmp)
      console.log(p);
    console.log("--------------");

    for (p in tmp)
      document.write(p + "--" + tmp[p] + '<br>');
  </script>
</body>

</html>

if i use delete tmp.pro the result:x=1 y=2 z=3 (is dosn't work!!), but when i use delete tmp[pro] the result is x=1 (delete is ok!!),why ??

Tushar
  • 85,780
  • 21
  • 159
  • 179
Likai
  • 29
  • 5

1 Answers1

1

pro is a string, otherwise the JavaScript is interpreting it as a pro property that exists on tmp. When you use square brackets, it is another way to refer to the property by name.

These are equivalent:

// #1
bar['baz']

// #2
bar.baz

// #3
var prop = 'baz';
bar[prop]
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445