我有以下一段代码,在我将 Prototype.js 包含到页面中后,它开始中断。
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));
});
}
}
它在以下几行处中断并出现错误
Uncaught TypeError: Object #<Object> has no method 'match'
a = a.match(/^\d+$/) ? +a : a;
b = b.match(/^\d+$/) ? +b : b;
最佳答案
您的问题很可能始于这一行:
for (var p in propPath) {
将prototype.js添加到页面后,您将无法使用常见(但不正确)的快捷方式,即使用for(foo in bar)
迭代数组。这是因为数组元素不再是简单的字符串或 float ,它们是成熟的“扩展”对象,如果正确地迭代它们,它们恰好会计算回字符串或 float 。
for(var i = 0; i < propPath.length; i++) {
会让你回到正轨。
关于javascript 与原型(prototype) js 冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21163392/