How to trim off last character in an Array - jQuery
所以今天我有一个数组,里面有几个字符串,都以,例如:爵士乐,拉丁语,恍惚,
我需要从数组的最后一个元素中删除。搜索stackoverflow时,我找到了几个答案,并尝试了下面的代码,但到目前为止还没有运气:(
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | // How I'm generating my Array (from checked checkboxes in a Modal) role_Actor = []; $('.simplemodal-data input:checked').each(function() { role_Actor.push($(this).val()); }); // roleArray = my Array var lastEl = roleArray.pop(); lastEl.substring(0, lastEl.length - 1); roleArray.push($.trim(lastEl)); // My function that displays my strings on the page $.each(roleArray, function(index, item) { $('.'+rowName+' p').append(item+', '); }); // Example of the Array: Adult Animated, Behind the Scenes, Documentary, |
谢谢你看!
谢谢@Claire Anthony!为修复!!!!
您忘记分配
正如注释所建议的那样,由于您只是将其用于显示目的,因此应该从
1 2 | var roleArray = ['latin', 'jazz', 'trance']; $('#example').append(roleArray.join(', ')); |
编辑现在他的问题已经被编辑以反映现实,这不再有效…=)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | // make an array var a = ['one,two,three,', 'four,five,six,']; // get the last element var lastEl = a[a.length -1]; // knock off the last character var trimmedLast = lastEl.substring(0, lastEl.length - 1); alert(trimmedLast); // as a function that will return said // please note you should write error handling and so // on in here to handle empty or non-array inputs. function lastArrayThing(myArray) { var lastEl = a[a.length -1]; return lastEl.substring(0, lastEl.length - 1); } alert( lastArrayThing(a) ); |
实际代码:http://jsfiddle.net/sb25j/
试试这个:
1 2 3 | $.each(arr, function(i, val) { arr[i] = val.substring(0, val.length - 1); }); |