I defined an array like
let a = [4,5,6]
then I attached a property to a like
a.stuff = 'hi'
For some reason, there is no error and if I stringify in html tags it doesn't show the stuff property but it does show in the browser console.
What kind of data type is it now? An array or some kind of hybrid? Is it good practice to do things this way? Why doesn't the stuff property show in html tags?
CodePudding user response:
The array's object properties and list of array elements are separate, and the array's traversal and mutation operations cannot be applied to these named properties.
let a = [4,5,6]
a.stuff = 'hi'
for (let el of a) {
console.log(el);
}
CodePudding user response:
You can always find it out yourself using the typeof operator which you can find right here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof . But in general JS arrays are considered object. And an object as well after trying to attach a property to it.
CodePudding user response:
It's kind of both Array and Object. This can be seen by simply using the console:
console.log(a)
[4, 5, 6, stuff: 'hi']
0: 4
1: 5
2: 6
stuff: "hi"
length: 3
[[Prototype]]: Array(0)
console.log(a instanceof Array)
true
console.log(a instanceof Object)
true
Note that in JavaScript an Array is an Object (check this article).
CodePudding user response:
It is always an 'object'.
let a = [4,5,6]
console.log('a:', a) // a: [4,5,6]
console.log('typeof a: ', typeof a); // typeof a: object
a.stuff = 'hi';
console.log('a:', a) // a: [4, 5, 6]
console.log('typeof a: ', typeof a); // typeof a: object
CodePudding user response:
Arrays are objects theirselves, once you added a property to it, it becomes an object with named property.