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'}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With