0

I have a javascript code within an html file. My goal is to display the list properties and methods of a given object. This is the code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Display properties and methods from objects</title>
</head>
<body>
    <script type="text/javascript">
    var tuna = 'tuna'
    var listPropertiesMethods = Object.getOwnPropertyNames(tuna)
    for (i=0; i<listPropertiesMethods.length; i++){
        console.log(listPropertiesMethods[i])
    }
    </script>
</body>
</html>

As u can see I am using the method Object.getOwnPropertyNames to get the list of properties of my object (variable) tuna.

The output that I get to the console is this:

0
1
2
3
length

I understand the method length because if I type tuna.length I get the number of characters of the variable. However if I type tuna.0 or tuna.1 I get error! What are those 0, 1, 2, 3 properties/methods? how can I use them?

PS: I am beginner...

Federico Gentile
  • 5,650
  • 10
  • 47
  • 102
  • `console.info(listPropertiesMethods);` will show all the object properties – smarber Jan 05 '18 at 11:03
  • @smarber How come other methods like indeOf() do not show up in the list? if I type for example tuna.indexOf() I get a number so I guess it's a method but apparently it's not listed... – Federico Gentile Jan 05 '18 at 12:33
  • 1
    Since `indexOf` is an inherited méthod, so you'll find it inside `__proto__` part – smarber Jan 05 '18 at 13:46

1 Answers1

-1

Please look at the comments inside the code:

 var tuna = 'tuna'
var listPropertiesMethods = Object.getOwnPropertyNames(tuna)
for (i=0; i<listPropertiesMethods.length; i++){
    console.log(listPropertiesMethods[i])
}

// Why do I see 0, 1, 2, 3 and length?
// Because they are the keys of the object tuna (yes it's a string object)

// How do I display their values?
// You can do the following
console.log(tuna[0]);
console.log(tuna[1]);
console.log(tuna[2]);
console.log(tuna[3]);
console.log(tuna['length']);
smarber
  • 4,829
  • 7
  • 37
  • 78