skip to Main Content

We can check whether a variable is array-like or array by Checking if an object is array-like.

How to check if a variable is array-like but not an array?

Update 1:

What I have tried so far is:

const car = { type: "Fiat", model: "500", color: "white" };
const cars = ["Saab", "Volvo", "BMW"];

function sum(a, b, c) {
    console.log(Array.prototype.isPrototypeOf(arguments));
    return a + b + c;
}

console.log(Array.prototype.isPrototypeOf(car));
console.log(Array.prototype.isPrototypeOf(cars));
result = sum(1, 2, 3)

I have use function sum because the documentation says:

arguments is an array-like object

So far it yields correct result. Please let me know whether I am on the right track.

2

Answers


  1. Chosen as BEST ANSWER

    OP Here, The answer is derived from the referred question.

    var array = [];
    array['test1'] = 'property';
    array['test2'] = 'property';
    array[0] = 'value';
    array[1] = 'value';
    array[-1] = 'value';
    array[1.5] = 'float';
    array[001] = 'float';
    
    const car = { type: "Fiat", model: "500", color: "white" };
    const cars = ["Saab", "Volvo", "BMW"];
    
    function args_of_func(a, b, c) {
        return isArrayLike(arguments);
    }
    
    function isArrayLike(item) {
        if (!Array.isArray(item) &&
        !(item instanceof Array) &&
        !Array.prototype.isPrototypeOf(item) &&
        Object.prototype.toString.call(item) !== '[object Array]' &&
        Number.isInteger(item.length) &&
        item.hasOwnProperty("length") &&
        Array.prototype.hasOwnProperty.call(item, "length"))
        {
            return true;
        }
        return false;
    }
    
    console.log("For Object");
    console.log(isArrayLike(car));
    console.log("For Array");
    console.log(isArrayLike(cars));
    console.log("For Array-like");
    console.log(args_of_func(1, 2, 3));
    

    isArrayLike will return true for only array-like objects, and false for arrays or other type of objects.


  2. arguments in a function is an object with keys and values you do not need to check if it is array like.

    function sum(a,b,c){
      console.log(typeof arguments, arguments);
    
    }
    
    const car = { type: "Fiat", model: "500", color: "white" };
    const cars = ["Saab", "Volvo", "BMW"];
    
    sum(1,2,3)
    sum(car);
    sum(cars);
    sum(...cars);

    If you want to sum every value passed to function sum just loop throuht arguments using for..in loop

    function sum(){
      let total = 0;
      for(const key in arguments){
        total += arguments[key];
      }
      return total;
    }
    
    console.log(sum(1,2,3));
    
    // strings as arguments
    const cars = ["Saab", "Volvo", "BMW"];
    console.log(...cars);

    Make sure every arguments[key] is a number which can be summed otherwise strings will be concatenated

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search