我想使用 for 回圈在陣列中查找最小數字 50 次,然后使用 splice() 將其洗掉。最后我想得到一個升序的數字串列。我遇到的問題是我的程式只找到第一個陣列的最小數字而不是更新的陣列。
array=[]
for(i=0; i<50; i ) {
array[i]=parseInt(Math.random()*100 1);
}
min = Math.min(...array)
minindex = array.indexOf(min);
splice = array.splice(minindex, 1)
console.log(splice)
uj5u.com熱心網友回復:
一種直截了當的方法...
const array = Array
.from(
{ length: 50 },
() => parseInt(Math.random() * 100 1),
)
.sort((a, b) => a - b);
// mutate/shorten `array`, remove all values equal to the minimum value.
array.splice(0, array.lastIndexOf(array[0]) 1);
上述實作的證明......
const array = Array
.from(
{ length: 50 },
() => parseInt(Math.random() * 100 1),
)
.sort((a, b) => a - b);
console.log({
arrayLength: array.length,
minValue: array[0],
sorted: array,
});
// mutate/shorten `array`, remove all values equal to the minimum value.
array.splice(0, array.lastIndexOf(array[0]) 1);
console.log({
arrayLength: array.length,
shortened: array,
});
.as-console-wrapper { min-height: 100%!important; top: 0; }
通過主動洗掉/切片專案來改變陣列的類似任務可以基于更通用reject的方法......
function reject(targetArray, condition, target) {
const rejectedItemList = [];
let idx = targetArray.length;
const copy = [...targetArray];
// Processing the array from RIGHT to LEFT keeps the `idx` always in sync
// with both related array items, the one of the mutated and also the one
// of the non mutated version of the processed target array reference.
// Thus the `condition` always gets passed the non mutated shallow copy.
while (idx) {
if (
// take *sparse array* into account.
targetArray.hasOwnProperty(--idx) &&
// [item, idx, copy] called within `target` context.
condition.call((target ?? null), copy[idx], idx, copy)
) {
// keep filling the list of rejected items
// FROM its LEFT side while mutating the target array.
rejectedItemList.unshift(targetArray.splice(idx, 1)[0]);
}
}
// returns an array of rejected items
// but not the processed and mutated
// target array reference.
return rejectedItemList;
}
const array = Array
.from(
{ length: 50 },
() => parseInt(Math.random() * 100 1),
);
const minValue = Math.min(...array);
console.log({
arrayLength: array.length,
minValue,
array,
});
console.log({
rejectedItems: reject(array, value => value === minValue),
arrayLength: array.length,
sorted: array.sort((a, b) => a - b),
});
.as-console-wrapper { min-height: 100%!important; top: 0; }
uj5u.com熱心網友回復:
也許是這樣的?
const array = [];
//create array
for (let i = 0; i < 100; i ) {
array.push(Math.floor(Math.random() * 100));
}
for (let i = 0; i < 50; i ) {
array.splice(array.indexOf(Math.min.apply(Math, array)), 1)
}
array.sort()
console.log(array)
或者更簡單,array.sort()在開頭使用
const array = [];
//create array
for (let i = 0; i < 100; i ) {
array.push(Math.floor(Math.random() * 100));
}
array.sort();
for (let i = 0; i < 50; i ) {
array.splice(0, 1)
}
console.log(array)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/441072.html
標籤:javascript 数组 排序 拼接
