
js 数组处理:生成自定义长度数组
您提到的问题是处理一个固定范围长度(4-8)的数组 arr 并根据一个自定义输入的数字 num 生成一个指定长度的数据列表。
解决方案:
横向计算:
function createlistdata(list, num = 600) {
let count = list.reduce((n, i) => n + i.test, 0);
let step = num / count | 0; //向下取整
let data = list.map((item, index) => {
return array.from({ length: item.test }).map(citem => {
return {
min: 0,
max: 0,
};
});
});
let max = math.max(...list.map(i => i.test));
let value = 0,
idx = 1;
for (let index = 0; index < max; index++) {
data.foreach(item => {
if (item[index]) {
item[index].index = idx++;
item[index].min = value + 1;
value += step;
item[index].max = num < value + step ? num : value;
}
});
}
return data;
}竖向计算:
function createListData(list, num = 600) {
let count = list.reduce((n, i) => n + i.test, 0);
let step = num / count | 0; //向下取整
let value = 0,
idx = 1;
let data = list.map((item, index) => {
return Array.from({ length: item.test }).map(citem => {
let start = value;
value += step;
return {
index: idx++,
min: start + 1,
max: num < value + step ? num : value,
};
});
});
return data;
}以上就是如何用JS高效生成指定长度的自定义数组?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号