将某些数组元素移至数组前面 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/31 18:20:17
我们需要编写一个 JavaScript 函数,该函数接受一个数字数组。该函数应将所有 3 位整数移至数组的前面。
假设以下是我们的数字数组 −
const numList = [1, 324,34, 3434, 304, 2929, 23, 444];
示例
以下是代码 −
const numList = [1, 324,34, 3434, 304, 2929, 23, 444];
const isThreeDigit = num => num > 99 && num < 1000;
const bringToFront = arr => {
for(let i = 0; i < arr.length; i++){
if(!isThreeDigit(arr[i])){
continue;
};
arr.unshift(arr.splice(i, 1)[0]);
};
};
bringToFront(numList);
console.log(numList);
输出
这将在控制台中产生以下输出 −
[ 444, 304, 324, 1, 34, 3434, 2929, 23 ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

