2013-04-05 100 views
0

所以今天我跟在他们几个字符串数组,全部采用,例如结尾:爵士,拉丁,恍惚,如何修剪掉最后一个字符数组 - jQuery的

我需要删除,关闭数组中的最后一个元素。搜索Stackoverflow我发现了几个答案,并试图下面的代码,但至今没有运气:(

// 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!为修复!

+0

为什么字符串在结尾处逗号开始?你应该修复你的数组生成过程。你确定逗号实际上是字符串的一部分,并且数组没有空的最后一个元素吗? – 2013-04-05 14:56:55

+1

给出您正在修剪的示例数组 – theshadowmonkey 2013-04-05 15:00:10

+0

这些字符串没有','与他们,但我必须添加它们以使显示的内容看起来正确。我已经添加了我的函数,它的作用如上 – 2013-04-05 15:00:12

回答

4

你忘了指定lastEl把它放回至​​前:

lastEl = lastEl.substring(0, lastEl.length - 1);

由于意见建议,并作为你仅仅使用这个用于显示目的,您应该删除从元素的逗号​​和使用join方法,像这样:

var roleArray = ['latin', 'jazz', 'trance']; 
$('#example').append(roleArray.join(', ')); 
+0

这是最接近我的解决方案!但我正在显示双数组?最后,现在没有显示出来寿$。每个(roleArray,函数(指数,项目){ //$('.'+rowName+” P ')附加(项目+', '); $('。 '+ rowName +'p')。append(roleArray.join(',')); }); – 2013-04-05 15:10:18

+2

你完全不需要循环 – billyonecan 2013-04-05 15:12:09

+0

谢谢!这很好! – 2013-04-05 21:12:50

1

试试这个:

$.each(arr, function(i, val) { 
    arr[i] = val.substring(0, val.length - 1); 
}); 
1

编辑现在他的问题已被编辑,以反映现实,这将不再有效.... =)

// 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/