Arrays have a \"length\" property by default.
Can I add custom properties to them?
Without having to make them objects
Arrays are objects and therefore you can add your own properties to them:
var arr = [1, 2, 3]; arr.foo = 'bar';
Extending from other answers, here are the following ways of iterating over the array, excluding custom properties.
1) Using a standard for loop
for (let i = 0; i < arr_length; i++)
console.log(arr[i]);
or if not using ES6:
for (var i = 0; i < arr.length; i++)
console.log(arr[i]);
2) Using the for ... of
loop (ES6+)
for (let el of arr)
console.log(el)
3) Using Array.prototype.forEach
(ES6+)
arr.forEach(el => console.log(el));
or
arr.forEach(function(el) {
console.log(el);
});
Iterating over the array, including all properties (e.g custom properties, length
)
for (let prop in arr)
console.log(prop);
or if not using ES6:
for (var prop in arr)
console.log(prop);