从JavaScript中的数组中删除所有空索引
假设我们有一个这样的文字数组-
const arr = [4, 6, , 45, 3, 345, , 56, 6];
我们需要编写一个JavaScript函数来接收一个这样的数组,并就地从数组中删除所有未定义的元素。
我们只需要删除未定义的和空的值,而不是所有虚假的值。
我们将使用for循环遍历数组,并使用Array.prototype.splice()删除未定义的元素。
因此,让我们为该函数编写代码-
示例
为此的代码将是-
const arr = [4, 6, , 45, 3, 345, , 56, 6];
const eliminateUndefined = arr => {
for(let i = 0; i < arr.length; ){
if(typeof arr[i] !== 'undefined'){
i++;
continue;
};
arr.splice(i, 1);
};
};
eliminateUndefined(arr);
console.log(arr);输出结果
控制台中的输出将为-
[ 4, 6, 45, 3, 345, 56, 6 ]
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便