Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从阵列中删除_Javascript_Arrays - Fatal编程技术网

Javascript 从阵列中删除

Javascript 从阵列中删除,javascript,arrays,Javascript,Arrays,我正在尝试使用以下说明从数组中删除元素: 使用循环移动数组值,如下所示。从索引参数开始;对于长度小于的索引-将一个索引移到末尾 将当前索引处的数组值设置为以下索引处的数组值 Example: remove value at index 2 in List: a b c d e 0 1 2 3 4 before loop: a b c d e after loop

我正在尝试使用以下说明从数组中删除元素:

使用循环移动数组值,如下所示。从索引参数开始;对于长度小于的索引-将一个索引移到末尾 将当前索引处的数组值设置为以下索引处的数组值

       Example: remove value at index 2 in List: a  b  c  d  e

                           0  1  2  3  4
             before loop:  a  b  c  d  e
       after loop pass 1:  a  b  d  d  e  (index 2 copies 'd' from index 3)
       after loop pass 2:  a  b  d  e  e  (index 3 copies 'e' from index 4)
       (loop ends)
将阵列长度减少1;在JavaScript中,这会从数组中删除最后一个元素

为什么我的代码不起作用

这个._data=[a,b,c,d,e]; 长度{ 返回此值。_data.length; } removeindex{ 如果索引===this.length{ 删除此。_数据[this.length]; } 而索引} 你的代码太糟糕了,你不能在没有属性的东西上使用property.length,你应该初始化对象,然后调用它


.length是一个整数属性,而不是一种方法。我建议您使用Google的开发人员工具来调试代码。阅读一些常规调试技巧。为什么我的代码不起作用?请详细说明。错误消息?错误的结果?两者都有?你不应该使用delete。第二条指令告诉您只需减小.length。对于初学者,打开浏览器控制台,在不使用splice的情况下查看错误?使用循环?可能检查索引是否小于长度,否则即使不删除任何内容,也始终会弹出数组。
var arr = ["a", "b", "c", "d", "e"];
arr.splice(2, 1); /* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice */
/* ["a", "b", "d", "e"] */
var arr = ["a", "b", "c", "d", "e"];        
function remove(arr, index){
    if(Array.isArray(arr) && Number.isInteger(index) && index >= 0 && index < arr.length){
        for(var i = index; i < arr.length - 1; i++){
            arr[i] = arr[i + 1];
        }
        arr.pop(); /* https://stackoverflow.com/questions/19544452/remove-last-item-from-array */
    }
}   
remove(arr, 2);