简体   繁体   English

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

[英]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? 如何使用点表示法在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'} 

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(); 

Just like you said, modify the prototypes. 就像你说的那样,修改原型。

 function log(...k) { console.log.apply(console, k); } Array.prototype.log = function() { log.apply(null, ['['].concat(this).concat([']'])); }; Object.prototype.log = function() { let vals = ['{']; for (var key in this) { if (this.hasOwnProperty(key)) { vals.push(key, this[key]); } } vals.push('}'); log.apply(null, vals); }; ['hello', 'world'].log(); ({ hello: 'world' }).log(); 

Please don't just munge native prototypes indiscriminately. 请不要随意乱动原生原型。 This can (and most likely will) cause you massive headaches. 这可能(并且很可能会)导致您大量头痛。 Instead use Object.defineProperty() and define your new methods properly. 而是使用Object.defineProperty()并正确定义新方法。

 Array.prototype.log = Array.prototype.log; if(Array.prototype.log === undefined) { Object.defineProperty(Array.prototype, 'log', { enumerable: false, value: function () { (this).forEach(function(item){ console.log(item); }); } }); } Object.prototype.log = Object.prototype.log; if(Object.prototype.log === undefined) { Object.defineProperty(Object.prototype, 'log', { enumerable: false, value: function (el, offset) { var self = this; Object.keys(this).forEach(function(key){ console.log(key + ':', (self[key])); }); } }); } var testArr = [1, 2, 'foo', 'bar']; var testObj = {one: 1, two: 2, foo: 'bar'}; testArr.log(); testObj.log(); 

In javascript there is what is been called prototypes . 在javascript中有什么叫做prototypes Prototypes are also objects , that you can assign members ( methods properties )to. Prototypes也是objects ,您可以将成员( methods properties )分配给。 In your case , if you want to create a function that works for a particular primitive value, you have to add that particular function as a method to the prototype of the constructor function of the primitive value. 在您的情况下,如果要创建适用于特定原始值的函数,则必须将该特定函数作为方法添加到原始值的构造函数的原型中。 For example in your case, you have to create a function as a method on the prototype of the Array and Object constructor functions 例如,在您的情况下,您必须在ArrayObject构造函数的原型上创建一个函数作为方法

example

Array.prototype.log = function() {    
    for ( let __elements of this ) {
        // uh
        // incase it's an array of array
        if ( Array.isArray(__elements) ) {
            __elements.log();
        } else {
            console.log(__elements);
        }
    } 
};



Object.prototype.log = function() {
    for ( let _prop in this ) {
        // typeof [] always returns an object
        if ( this.hasOwnProperty(_prop) ) {
            if ( typeof this[_prop] === 'object' && ! 
                Array.isArray(this[_prop]) ) {
                this[_prop].log();
            } else {
                console.log(this[_prop]);
            }
        }
    }
};


[1,2,3,4].log();

[[1,2,[3,4]],3,[2]].log();

let obj = {
    name:"victory",
    surname: "osikwemhe",
    life: {
        occupation: ["accontant","programmer"],
        hobbies: "danching gnamgnam style",
        hates: "sharing my wifi",
        tvshows: {
            "cw": ["the flash"],
            "hbo": ["silicon valley"],
            "history": ["vikings"]
        }        
    } 
};


obj.log();

in case you are worthering what the this point to, this points to the primitive value we use the log method on 如果你正在调整this一点, this指向我们使用log方法的原始值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在winston中记录JavaScript对象和数组作为console.log呢? - How to log JavaScript objects and arrays in winston as console.log does? Object 属性以点表示法调用,显示 console.log 'undefined' - Object property called with dot notation showing console.log 'undefined' 对象数组中的Javascript对象与console.log不同 - Javascript objects in array of objects,are different using console.log console.log() 对象不会记录通过节点 js 控制台中的原型添加的方法。 或者如何打印原型? - console.log() an object does not log the method added via prototype in node js console. Or how to print the prototypes also? 在网页中没有 [“{ and the }”] 的情况下,如何在 JavaScript console.log() 中打印出 [{ and }] ? - How do you print out [{ and }] in JavaScript console.log() without the [“{ and the }”] in web page? Angular2-您如何console.log当前路由? - Angular2 - How do you console.log the current route? 如何在 ES6 中控制台记录以下对象? - How do I console.log the following objects in ES6? Javascript:console.log 与 colors 和对象 - Javascript: console.log with colors and objects 如何在Handlebars模板中添加console.log()JavaScript逻辑? - How do I add console.log() JavaScript logic inside of a Handlebars template? 如何在JavaScript文件console.log中添加Rails控制器变量? - How do I add a rails controller variable to javascript file console.log?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM