繁体   English   中英

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

[英]Javascript: How do I splice a value from an array with an index of 0?


我试图使用splice从数组中删除一个值。 从0开始到0拼接结束,但它没有删除索引0处的值。我添加了一个函数getItemRow来检查返回0的种类索引。我将数组的值转储到一个警报中它仍然输出物种应该被删除。 invalidElement.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')
});

我想你想splice(0, 1)

第二个参数是你想删除多少...

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

来源

还有一个便利功能,用于删除数组中的第一个元素:

array.shift();

请参阅: https//developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/shift

拼接可以两种模式工作; 删除或插入项目。

删除项目时,您将指定两个参数: splice(index, length)其中index是起始索引,length是要删除的元素的正数(fyi:传递“0”,如示例中所示,不执行任何操作 - - 这是说“删除从索引开始的零项”)。 在你的情况下,你会想要:

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");

Mozilla开发中心 - Array.splice声明第二个参数是要删除的'howMany'元素。

我不确定你的代码在indexValue中作为要删除的元素数传递时的工作方式,除非你从数组的末尾删除。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM