在数组的 falsy 索引处插入元素 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/19 14:04:17
我们需要编写一个数组函数,比如说 pushAtFalsy()。该函数应接受一个数组和一个元素。它应将元素插入到它在数组中找到的第一个 falsy 索引处。
如果没有空格,则应将元素插入到数组的最后。
我们将首先搜索空位置的索引,然后用我们提供的值替换那里的值。
示例
以下是代码 −
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 ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

