Iterate over object keys in node.js

后端 未结 5 1735
伪装坚强ぢ
伪装坚强ぢ 2020-11-30 23:12

Since Javascript 1.7 there is an Iterator object, which allows this:

var a={a:1,b:2,c:3};
var it=Iterator(a);

function iterate(){
    try {  
        consol         


        
5条回答
  •  旧巷少年郎
    2020-12-01 00:00

    adjust his code:

    Object.prototype.each = function(iterateFunc) {
            var counter = 0,
    keys = Object.keys(this),
    currentKey,
    len = keys.length;
            var that = this;
            var next = function() {
    
                if (counter < len) {
                    currentKey = keys[counter++];
                    iterateFunc(currentKey, that[currentKey]);
    
                    next();
                } else {
                    that = counter = keys = currentKey = len = next = undefined;
                }
            };
            next();
        };
    
        ({ property1: 'sdsfs', property2: 'chat' }).each(function(key, val) {
            // do things
            console.log(key);
        });
    

提交回复
热议问题