Javascript: 如何从索引为0的数组中删除一个值?

12


我试图使用splice从数组中删除一个值。从0开始到0结束的splice,但它没有删除索引为0的值。我添加了一个名为getItemRow的函数来检查该物种的索引,它返回0。我将数组的值转储到警报中,并且仍然输出应该已被删除的species。无效元素.splice(indexValue,indexValue);适用于不是0的索引。为什么会这样,如何删除具有索引为0的值?

JavaScript代码:

var invalidElement = new Array("species", "alias", "gender", "breeding", "birth_date");

//This function will be removed once fixed!!
function getItemRow()
{
    var myPosition=-1
    for (i=0;i<invalidElement.length;i++)
    {
        if(invalidElement[i]=="species") {
            myPosition = i;
            break;
        }
    }
    alert(myPosition)
}

function validateElement(formId, element, selector, errorContainer)
{
    getItemRow()//for testing purposes
    //var indexValue = $.inArray(element, invalidElement);
    var indexValue = invalidElement.indexOf(element);

    alert(element);
    $.ajax({
        type: 'POST',
        cache: false,
        url: "validate_livestock/validate_form/field/" + element,
        data: element+"="+$(selector).val(),
        context: document.body,
        dataType: 'html',
        success: function(data){
            if (data == "false")
            {
                $(errorContainer).removeClass('element_valid').addClass('element_error');
                invalidElement = element;
                alert(invalidElement.join('\n'))//for testing purposes
                //alert(indexValue);
            }
            else
            {
                $(errorContainer).removeClass('element_error').addClass('element_valid');
                invalidElement.splice(indexValue, indexValue);
                alert(invalidElement.length);//for testing purposes
                alert(invalidElement.join('\n'))//for testing purposes
            }
        }
    });
}

$("#species").change(function(){
    validateElement('#add_livestock', 'species', '#species', '.species_error_1')
});
4个回答

16

我认为你想要使用 splice(0, 1)

第二个参数是指你想要移除多少个元素...

一个整数,表示要删除的旧数组元素数量。如果 howMany 为 0,则不会删除任何元素。

来源


1
我误解了如何使用splice。谢谢你的帮助。 - dottedquad
我还注意到,如果我通过数组中列出的元素进行验证,invalidElement.splice(indexValue, 1)也可以很好地工作。 - dottedquad

14

splice有两种模式:删除或插入项目。

当删除项目时,您需要指定两个参数:splice(index, length),其中index是起始索引,length是要删除的元素数量(提示:如您的示例中传递“0”,则什么都不会发生——它表示“从index开始删除零个项目”)。在您的情况下,您需要:

invalidElement.splice(indexValue, 1); // Remove 1 element starting at indexValue

在插入元素时,你需要指定(至少)三个参数:splice(index, length, newElement, *additionalNewElements*)。在这种情况下,通常将第二个参数传递为0,这意味着要在现有元素之间插入新元素。

 var invalidElements = ["Invalid2", "Invalid3"];
 invalidElements = invalidElements.splice(0, 0, "Invalid1");

如果您想插入一个元素数组,请查看此答案:https://dev59.com/_nRB5IYBdhLWcg3wkH5N#12189963 - Luis Perez

11

0

Mozilla Dev Center - Array.splice指出第二个参数是要删除的“howMany”元素数量。

我不确定当您将indexValue作为要删除的元素数量传递时,您的代码是如何工作的,除非您是从数组末尾删除。


如果出现这种情况,那将是一个有趣的 bug。如果 indexValue === 1,则会删除从索引 1 开始的 1 个项目。如果 indexValue === 2,则会删除从索引 2 开始的 2 个项目,以此类推。 - STW
哈哈,我想你的意思是完全正确的。 - Brian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接