gpt4 book ai didi

javascript - 如何在数组中获取连续的空格javascript

转载 作者:行者123 更新时间:2023-11-28 18:18:06 25 4
gpt4 key购买 nike

我有这个功能:

 function insertValue2(cantidad, value, arr){

var spaceCount = 0;

arr.forEach(function(item, index) {
if(item == "") {
console.log(index)
spacecount++;
}
});
console.log(spaceCount)

我的函数计算此数组中的空格:["", "", "", "B", "B", "B", ""]

所以结果是:0 1 2 6是数组中带有空格的位置,spacecount = 4

我不知道这是否可能,但知道如何在获得第一个 B 之前计算空格吗?

我的意思是计算连续的空格,例如 0 1 2 spacecount = 3然后计算 6 spacecount = 1 的空间

如果我想插入我的数组 quantity = 1value = C这将选择 spacecount 的最低值。

["", "", "", "B", "B", "B", "C"]

编辑:

数量是我将在数组中使用多少空间,我不想使用超过数量所需的空间

在此数组中,我的位置 0, 1, 2, 7 , 8, 9, 10 有空格

["", "", "", "B", "B", "B", "C", "" , "" ,"" ,""]

如果我想插入quantity = 2value = D ,预期结果为:

["D", "D", "", "B", "B", "B", "C", "" , "" ,"" ,""]

如果我想插入quantity = 1 and value = "E"它将选择position 2spacecount = 1来保存数量较多时需要更高的空间数,例如 3 或 4

["D", "D", "E", "B", "B", "B", "C", "" , "" ,"" ,""]

感谢您的帮助:)

最佳答案

您只需迭代数组一次,检查是否为项目并保留数组数组,其中每个项目都是具有所需值的索引组,在您的情况下为空字符串。

一种方法是扩展 Array 对象本身:(请参阅控制台了解结果)

Array.prototype.groupBy = function(value) {
var array = this;
var groups = [];
var buffer = [];
for (var i = 0; i < array.length; i++) {
var curItem = array[i];
if (curItem == value) {
buffer.push(i);
} else if (buffer.length > 0) {
groups.push(buffer);
buffer = [];
}
}
if (buffer.length > 0)
groups.push(buffer);
return groups;
};

var a = ["", "", "", "B", "B", "B", ""];
var consecutiveBlankSpaces = a.groupBy("");
console.log('total of ' + consecutiveBlankSpaces.length + ' groups of blank spaces');
for (var i = 0; i < consecutiveBlankSpaces.length; i++) {
console.log('Found a blank space group consisting of ' +
consecutiveBlankSpaces[i].length + ' items, indexes: ' +
consecutiveBlankSpaces[i]);
}

关于javascript - 如何在数组中获取连续的空格javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40460192/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com