getJSON响应中自定义jQuery reverse插件失效问题求助
Let's break down why your reverse plugin isn't working and get it sorted out step by step:
1. What's Going Wrong Here?
Your custom reverse plugin is built for jQuery DOM element collections (like $('li') or $('.item')), not plain JavaScript arrays—which is exactly what your $response from getJSON is. On top of that, you're calling the plugin incorrectly:
- You’re invoking
$.fn.reverse()directly from the jQuery prototype, instead of using it on a jQuery instance. - The plugin’s
thiscontext isn’t set to your array, so the loop logic never executes properly (it can’t accessthis.lengthfor your array).
2. Simple Fixes to Reverse Your JSON Response
You’ve got a few straightforward options to get the reverse iteration working:
Option 1: Use Native Array Methods (Easiest)
Since $response is a plain JS array, you don’t need a jQuery plugin at all. Use native methods to safely reverse the order without modifying the original array:
// Create a copy of the array, reverse it, then iterate $response.slice().reverse().forEach(function(v) { $("#selector").append('<tr><td>' + v.name + '</td></tr>'); });
slice()makes a shallow copy of the array so we don’t mess up the original$response.reverse()flips the copied array’s order.forEach()loops through the reversed array to build your table rows.
Option 2: Update the Plugin to Support Arrays
If you want to keep using a custom reverse utility, tweak it to work with both jQuery collections and plain arrays:
(function ($) { // Utility function for arrays $.reverse = function(arr, fn) { var i = arr.length; while(i--) { fn.call(arr[i], i, arr[i]); } }; // Keep the original plugin for DOM elements (maintains chainability) $.fn.reverse = function(fn) { $.reverse(this, fn); return this; }; }(jQuery));
Then call it for your JSON array like this:
$.reverse($response, function(k, v) { $("#selector").append('<tr><td>' + v.name + '</td></tr>'); });
Option 3: Manual Backward Loop
If you prefer to skip plugins and native methods entirely, just loop backward through the array directly:
var i = $response.length; while(i--) { var v = $response[i]; $("#selector").append('<tr><td>' + v.name + '</td></tr>'); }
3. Why Your Original Code Failed
When you wrote $.fn.reverse($response, function(...)), you passed $response as the first argument—but the plugin expects this to be the collection/array it’s operating on. Instead, this was set to the jQuery prototype ($.fn), so this.length was undefined, and the loop never ran.
内容的提问来源于stack exchange,提问作者Jacques

