best practice looping through javascript object
This question already has an answer here:
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中循环数组