best practice looping through javascript object

This question already has an answer here:

  • Access / process (nested) objects, arrays or JSON 18 answers
  • For-each over an array in JavaScript? 23 answers

  • You can do a test like this

    function representsNumber(str) {
        return str === (+str).toString();
    }
    
    // e.g. usage
    representsNumber('a'); // false
    representsNumber([]); // false
    representsNumber(1); // false (it IS a number)
    representsNumber('1.5'); // true
    representsNumber('-5.1'); // true
    representsNumber('NaN'); // true
    

    And recurse over all your nodes, overkill example

    function seeker(o, test, _true, _false) {
        _true || (_true = function (e) {return e;});
        _false || (_false = function (e) {return e;});
        function recursor(o) {
            var k;
            if (o instanceof Array)
                for (k = 0; k < o.length; ++k) // iterate over array
                    if (typeof o[k] !== 'object')
                        o[k] = test(o[k]) ? _true(o[k]) : _false(o[k]);
                    else
                        recursor(o[k]);
            else
                for (k in o) // iterate over object
                    if (typeof o[k] !== 'object')
                        o[k] = test(o[k]) ? _true(o[k]) : _false(o[k]);
                    else
                        recursor(o[k]);
        }
        if (typeof o === "object") return recursor(o), o;
        else return test(o) ? _true(o) : _false(o); // not an object, just transform
    }
    
    // e.g. usage
    seeker({foo: [{bar: "20"}]}, representsNumber, parseFloat);
    // {foo: [{bar: 20}]}
    
    链接地址: http://www.djcxy.com/p/12058.html

    上一篇: 在Javascript中循环数组

    下一篇: 通过JavaScript对象循环的最佳实践