I have following piece of code and this has started breaking after i included Prototype.js into the page.

          function JsonArrayByProperty(objArray, prop, direction) {
            if (arguments.length < 2) throw new Error("sortJsonArrayByProp requires 2 arguments");
            var direct = arguments.length > 2 ? arguments[2] : 1; //Default to ascending

            if (objArray && objArray.constructor === Array) {
                var propPath = (prop.constructor === Array) ? prop : prop.split(".");
                objArray.sort(function (a, b) {
                    for (var p in propPath) {
                        if (a[propPath[p]] && b[propPath[p]]) {
                            a = a[propPath[p]];
                            b = b[propPath[p]];
                        }
                    }
                    a = a.match(/^\d+$/) ? +a : a;
                    b = b.match(/^\d+$/) ? +b : b;
                    return ((a < b) ? -1 * direct : ((a > b) ? 1 * direct : 0));
                });
            }
        }

It breaks at following lines with error

   Uncaught TypeError: Object #<Object> has no method 'match' 

   a = a.match(/^\d+$/) ? +a : a;
   b = b.match(/^\d+$/) ? +b : b;
有帮助吗?

解决方案

Your problem most likely starts on this line:

for (var p in propPath) {

Once you add prototype.js to your page, you cannot use the common (but incorrect) shortcut of iterating over an array using for(foo in bar). That's because array elements are no longer simple strings or floats, they are full-fledged "extended" objects that happen to evaluate back to strings or floats if you iterate over them correctly.

for(var i = 0; i < propPath.length; i++) {

will get you back on track.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top