如何修剪数组中的最后一个字符 - jQuery

时间:2013-04-05 14:55:14

标签: jquery arrays trim

所以今天我有一个包含几个字符串的数组,所有字符串结尾,例如:jazz,latin,trance,

我需要删除数组中最后一个元素。正在搜索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!为修复!!!

3 个答案:

答案 0 :(得分:4)

您在忘记lastEl之前忘记分配roleArray

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

正如评论所示,并且您只是将其用于显示目的,您应该从roleArray中的元素中删除逗号并使用join方法,如下所示:

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

答案 1 :(得分:1)

试试这个:

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

答案 2 :(得分: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/