我希望函数将所有3位整数返回到数组的前面。当我控制台登录时,我得到8个阵列,其中没有一个是我正在寻找的输出。我怀疑当我开始使用for()时错误开始。
此外,有关如何进一步清理代码的任何提示都值得赞赏,因为我正在学习最佳实践。
let numList = [1, 324,34, 3434, 304, 2929, 23, 444]
function checkLength (num){
num.forEach(function (n){
var stringLength = n.toString().length; //n = 324, 204, 444
for (i=0; i<num.length; i++){
if (stringLength == 3){
let a = num.splice (i,1);
num.unshift (a[0]);
}
}
})
console.log(num);
}
checkLength(numList);
答案 0 :(得分:1)
Reduce数组为3位数组,其余数组,然后通过传播到Array.concat()
将它们展平为单个数组:
function checkLength(array) {
return [].concat(...array.reduce((r, n) => {
r[n > 99 && n < 1000 ? 0 : 1].push(n);
return r;
}, [[], []]));
}
console.log(checkLength([1, 324, 34, 3434, 304, 2929, 23, 444]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:0)
我认为你对 Shift 的工作原理感到困惑......
shift()方法从数组中删除第一个元素并返回已删除的元素
它不会将所有3位数的整数带到前面,它只会从数组中删除第一个元素,这将会返回。
我认为您正在寻找排序或过滤数组。
如果您希望按其值的长度排序数组,这是一种方法:.sort(a=>a.toString().length!=3?1:-1)
let numList = [1, 324,34, 3434, 304, 2929, 23, 444]
console.log(numList.sort(a=>a.toString().length!=3?1:-1))
如果您想过滤几乎相同:
let numList = [1, 324,34, 3434, 304, 2929, 23, 444]
console.log(numList.filter(a=>a.toString().length==3?1:0))
答案 2 :(得分:0)
基本上你需要一个长度为3的第一项索引和另一个用于迭代数组的索引。
如果一个项目的字符串长度为3,则拼接该项目并将其放回存储的索引中。然后递增该索引。
继续循环。
此提案保留了商品的顺序。它只是将字符串长度的项目移动到,同时保持这些项目的顺序。
function checkLength(array) {
var i = 0,
j;
for (j = 0; j < array.length; j++) {
if (array[j].toString().length === 3) {
array.splice(i++, 0, array.splice(j, 1)[0]);
}
}
return array;
}
console.log(checkLength([1, 324, 34, 3434, 304, 2929, 23, 444]));
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
答案 3 :(得分:0)
您可以只检查范围,而不是将数字转换为字符串。找到3位数后,我们会使用splice()
将其从数组中删除,然后使用.unshift()
将其添加到数组前面。
let numList = [1, 324, 34, 3434, 304, 2929, 23, 444];
function checkLength(num) {
num.forEach((v, i, a) => {
if(v > 99 && v < 1000) {
a.unshift(...a.splice(i, 1));
}
});
return num;
}
console.log(checkLength(numList));
&#13;
答案 4 :(得分:0)
为什么使用嵌套循环?
你可以这样做:
var arr = [1, 324,34, 3434, 304, 2929, 23, 444];
function checkLength (arr){
arr.forEach(function (n, index){
if (n >= 100 && n < 1000) {
arr.unshift(arr.splice(index, 1)[0]);
}
});
return arr;
}
checkLength(arr);
请注意,修改正在循环的阵列可能会很危险,并可能导致您不希望出现的情况。
答案 5 :(得分:0)
请查看代码。我希望你不言自明。基本上,这里有2个选项:
我在下面的代码中使用第一种方法:
function shiftThreeDigitValuesInFrontOfArray(array)
{
var threeDigitValue; // Will hold the value later,
array.forEach(function(element, index)
{
// We are only interested in 3 digit values
if(element.toString().length === 3)
{
// Remove the value from the array
threeDigitValue = array.splice(index, 1);
// And put it in front of the array
array.unshift(threeDigitValue[0]);
}
});
}
var array = [1, 324,34, 3434, 304, 2929, 23, 444];
// Let the magic begin!
shiftThreeDigitValuesInFrontOfArray(array);
// View the results
console.log(array);
请告诉我这是否适合您:)