2021年2月3日星期三

Why does the variable used in the [For.. in] loop return different values when the object is a JSON object vs an Array object?

I have divided this question into two sub-parts, because they are related, and to make it easier to understand.

var outside = ['laptop', 'tv', 'car'];  for (p in outside) {      var message = p;      console.log(message);  }

Now, here we have an Array, and the variable p jumps through all properties, in this case, array items, and assigns to itself the index number of the items. So, 1..2..3. This allows me to then do this:

var outside = ['laptop', 'tv', 'car'];      for (p in outside) {          var message = outside[p];          console.log(message);      }

..use the variable p as a numerical substring to return the property name of each array item.

Now, two questions here:

  1. If the variable goes through properties, like its description says, then why does using it on an array, the variable assigns the index numerical value of the items?
  2. Why does using outside[number] returns the name of the property?

One explanation that would make sense is if each array item is actually an object, and obviously the substring [number] returns the name of that object, where as the for..in variable jumps through each property of the array item objects, and their properties are actually the index number, so that's what it returns.

Is that explanation right, or completely wrong?

The second part of my question is using JSON objects.

var marry = '{"age":"30","height":"180","eyecolor":"blue"}';    var maryobject = JSON.parse(marry);    var out = "";    for (i in maryobject) {   out = i;    console.log(out);   }

Now, here the variable i returns the property names of the object.

However, using the variable i as a substring like I did before with the Array, returns the value of the properties:

    var marry = '{"age":"30","height":"180","eyecolor":"blue"}';        var maryobject = JSON.parse(marry);        var out = "";        for (i in maryobject) {       out = maryobject[i];        console.log(out);       }

Now, two questions here too:

  1. Why does [i] indicate the position of the property, since [i] is not a numerical value?

  2. Why does maryobject[i] returns back the value of the property?

https://stackoverflow.com/questions/66037251/why-does-the-variable-used-in-the-for-in-loop-return-different-values-when-t February 04, 2021 at 07:28AM

没有评论:

发表评论