首页 文章资讯内容详情

在数组的伪索引处插入元素-JavaScript

2026-06-04 1 花语

我们需要编写一个Array函数,比如pushAtFalsy(),该函数应该包含一个数组和一个元素。它应该将元素插入在数组中找到的第一个虚假索引处。

如果没有空格,则元素应插入数组的最后。

我们将首先搜索空头指数,然后用我们提供的值替换那里的值。

示例

以下是代码-

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 ]