Given the following snippet:
const myArray = ["foo", "bar", "baz"];
myArray.someProperty = "foobar";
console.log(myArray)
In Safari, it will display only this:
["foo", "bar", "baz"] (3)
In other browsers, like Chrome and Firefox, it will display the someProperty
property, along with native properties like length
:
Array(3)
0: "foo"
1: "bar"
2: "baz"
someProperty: "foobar"
length: 3
It's worth mentioning that things like console.dir
, console.table
or console.log(JSON.stringify(myArray))
won't work for displaying such properties.
Is there any workaround for this limitation in Safari? Obviously I could just do console.log(myArray.someProperty)
, but my main goal is checking what properties the array have (I'm not the one creating the array, it's being created by a JS library), so those properties are unknown to me.
Just pass the Array object into a console. log() to print the array as comma-separated in JavaScript. And if you want to print array elements wise then use loop (while or for-loop).
The console. table() method displays tabular data as a table. This function takes one mandatory argument data , which must be an array or an object, and one additional optional parameter columns .
The find() method returns the value of the first element that passes a test. The find() method executes a function for each array element. The find() method returns undefined if no elements are found.
You need to convert it to Object first
console.log(Object.assign({}, myArray))
It will show all of your array properties
Based on the accepted answer I can even strip the numeric keys (which are the common array content) and log only the array's properties, if any:
const myArray = ["foo", "bar", "baz"];
myArray.someProperty = "foobar";
myArray.someOtherProperty = "barbaz";
logArrayProperties(myArray)
function logArrayProperties(arr) {
Object.entries(Object.assign({}, arr)).forEach(row => {
if (isNaN(row[0])) console.log(row[0] + ": " + row[1])
});
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With