0

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.

9
  • 4
    Add && !Array.isArray(variable) Commented May 25, 2023 at 16:59
  • ...or !(variable instanceof Array). Commented May 25, 2023 at 17:01
  • I am assuming it has Array.prototype.forEach method then it is array-like. Commented May 25, 2023 at 17:03
  • @AhmadIsmail If an object supports .forEach() it doesn't mean it's array-like. Commented May 25, 2023 at 17:24
  • Updated the question with details. Commented May 25, 2023 at 17:28

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

3 Comments

I know i do not "check if it is array like". I used the argument just to have an array-like object. The question is not about how to use the arguments variable.
@AhmadIsmail In this case maybe this article can help link
Thank you very much. I am going through it right now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.