Add property to javascript array

后端 未结 5 1729
不思量自难忘°
不思量自难忘° 2020-11-28 10:24

Arrays have a \"length\" property by default.

Can I add custom properties to them?

Without having to make them objects

5条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 10:51

    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);
    

提交回复
热议问题