如何使用点表示法将 console.log 方法添加到 JavaScript 中的数组和对象原型?

Ric*_*ick 3 javascript logging

如何使用点表示法在 javascript 中的数组和对象上创建日志方法?

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'}
Run Code Online (Sandbox Code Playgroud)

Chr*_*tos 5

您可以将此方法添加到数组的原型中,如下所示:

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

关于对象,您可以通过将函数添加到对象原型来执行相同的操作:

var obj = { 'hello' : 'world' };
Object.prototype.log = function(){
  Object.keys(this).forEach(function(key){
      console.log(key);
      console.log((obj[key]));
    });
};
obj.log();
Run Code Online (Sandbox Code Playgroud)