Home > Net >  being function and an array at same time?
being function and an array at same time?

Time:10-10

I wonder why is that:

function greeting(){
    alert('hello sir...')
}

greeting();

greeting[0] = "zero"
greeting[1] = "one"
greeting[3] ="two"
greeting[4] ="three"
greeting[5] ="four"
greeting[6] ="five"
greeting[7] ="six"

console.log(greeting[5]) outputs four

greeting.map(i=>{
    console.log(i)
})

// here compaints .map is not a function

so how can greeting be trated like an Array but has not .map function??

CodePudding user response:

You can assign indexed properties on any object - including function objects - but that doesn't make them arrays. They neither gain a .length nor array methods.

function useLikeAnArray(obj) {
  console.log(obj);
  obj[0] = "zero"
  obj[1] = "one"
  obj[2] = "two";
  obj.length = 3;
  console.log(obj);
  Array.prototype.forEach.call(obj, el => console.log(el));
}

useLikeAnArray(function greeting() {});
useLikeAnArray({simple: "object"});
useLikeAnArray(null); // oops

CodePudding user response:

You could convert the function, or any other object to an array and iterate with a native method.

function greeting() {
    console.log('hello sir...');
}

greeting();

greeting[0] = "zero";
greeting[1] = "one";
greeting[3] = "two";
greeting[4] = "three";
greeting[5] = "four";
greeting[6] = "five";
greeting[7] = "six";

console.log(greeting[5]);

Object.assign([], greeting).forEach(v => console.log(v));

CodePudding user response:

You can assign properties to a function but it is still a function. Here we can see all the properties and the type of those as well as the type of greeting

function greeting(){
   // alert('hello sir...')
}

greeting();

greeting[0] = "zero"
greeting[1] = "one"
greeting[3] ="two"
greeting[4] ="three"
greeting[5] ="four"
greeting[6] ="five"
greeting[7] ="six"
console.log("geeting greeting[5] is",typeof greeting[5],greeting[5]);
console.log("greeting is a:",typeof greeting);

for (var key in greeting) {
    if (Object.prototype.hasOwnProperty.call(greeting, key)) {
        var val = greeting[key];
     console.log("key:",key,greeting[key]);
    }
}

  • Related