0

所以今天我有一个数组,里面有几个字符串,都以 结尾,例如:爵士,拉丁,恍惚,

我需要删除 , 数组中的最后一个元素。搜索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,

谢谢参观!


谢谢@克莱尔安东尼!修复!!!

4

3 回答 3

4

lastEl您在将其放回之前忘记分配roleArray

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

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

var roleArray = ['latin', 'jazz', 'trance'];
$('#example').append(roleArray.join(', '));
于 2013-04-05T15:01:20.527 回答
1

试试这个:

$.each(arr, function(i, val) {
    arr[i] = val.substring(0, val.length - 1);
});
于 2013-04-05T15:01:12.353 回答
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/

于 2013-04-05T15:04:43.307 回答