Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you add a console.log method on to arrays and objects prototypes in JavaScript using the dot notation?

How can you create a log method on arrays and objects in javascript using the dot notation?

function log(...k){

console.log.apply(console, k)

}

log('hello') //=> prints hello


//I want to do this for arrays and objects using the dot notation


['hello','world'].log() //=> prints ['hello', 'world']


{'hello':'world'}.log() //=> prints {'hello', 'world'}
like image 354
Rick Avatar asked May 10 '26 08:05

Rick


1 Answers

You could add this method to the prototype of arrays, like below:

var array = ['hello','world'];
Array.prototype.log = function(){
    (this).forEach(function(item){
        console.log(item);
    });
};
array.log();

Regarding an object you could do the same by adding you function to the object prototype:

var obj = { 'hello' : 'world' };
Object.prototype.log = function(){
  Object.keys(this).forEach(function(key){
      console.log(key);
      console.log((obj[key]));
    });
};
obj.log();
like image 76
Christos Avatar answered May 11 '26 21:05

Christos