在数组中空索引处插入元素 - JavaScript
我们需要编写一个数组函数,例如 pushAtFalsy()。函数应该采用一个数组和一个元素。它应将元素插入到数组中发现的第一个假索引处。
如果没有空位,则应在数组末尾插入该元素。
我们将首先搜索空位置的索引,然后用我们提供的 value 替换那里的 value。
示例
以下是代码 −
const arr = [13, 34, 65, null, 64, false, 65, 14, undefined, 0, , 5, ,
6, ,85, ,334];
const pushAtFalsy = function(element){
let index;
for(index = 0; index < this.length; index++){
if(!arr[index] && typeof arr[index] !== 'number'){
this.splice(index, 1, element);
break;
};
};
if(index === this.length){
this.push(element);
}
};
Array.prototype.pushAtFalsy = pushAtFalsy;
arr.pushAtFalsy(4);
arr.pushAtFalsy(42);
arr.pushAtFalsy(424);
arr.pushAtFalsy(4242);
arr.pushAtFalsy(42424);
arr.pushAtFalsy(424242);
arr.pushAtFalsy(4242424);
console.log(arr);输出
这将在控制台生成以下输出 −
[ 13, 34, 65, 4, 64, 42, 65, 14, 424, 0, 4242, 5, 42424, 6, 424242, 85, 4242424, 334 ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP