javascript - 从 Strig 中删除 "," (并返回 RGB\n 字符串)
问题描述
所以我已经被这个问题困扰了几天:我的输入是这样的:
"255,255,255,10,251,91,31,4,220,220,220,1"
它是一个具有 3 个不同 RGB 值的字符串,它还带有一个数字,表示它们的数量从最高到最低。您可以将上面的字符串翻译为:
"RED1, GREEN1, BLUE1, QUANTITY1, RED2, GREEN2 ... "
1 代表第一种颜色,2 代表第二种,依此类推。
我需要返回的是没有数量的第一种颜色。所以我的输出应该是这样的:
"255,255,255,251,91,31,220,220,220"
我尝试了很多东西,一个是这个功能:
var firstC, secondC, thirdC;
var pointer = "firstC";
function getEachColorValue(color) {
var startIndex = 0;
var endIndex = 0;
for (var i = 0; i < color.length; i++) {
if (color.charAt(i) == ",") {
endIndex = i;
if (pointer == "firstC") {
firstC = color.substring(startIndex, endIndex);
startIndex = endIndex + 1;
pointer = "secondC";
} else if (pointer == "secondC") {
secondC = color.substring(startIndex, endIndex);
startIndex = endIndex + 1;
pointer = "thirdC";
} else if (pointer == "thirdC") {
thirdC = color.substring(startIndex, endIndex);
startIndex = endIndex;
pointer = "firstC";
}
}
}
}
这推动RED1
了firstC
, GREEN1
insecondC
和BLUE1
inthirdC
我曾经想过这样做,使用一个函数将 firstC,secondC,thirdC 写入数组,重置它们。然后切割成col3
没有第一个调色板的子串,然后重复。
// Global variables
var stringHolder;
var newString;
var counter = 0;
var colorSetHT = new Array;
// main
createSubstring(col3);
function createSubstring(color) {
var startIndex = 0;
var endIndex = 0;
for (var i = 0; i < color.length; i++) {
if (color.charAt(i) == ",") {
counter++;
endIndex = i;
}
if (counter == 4) {
stringHolder = color.substring(startIndex, endIndex);
alert(stringHolder);
newString = color.substring(endIndex+1, color.length);
getEachColorValue(stringHolder);
colorSetHT.push(firstC, secondC, thirdC)
colorReset();
counter = 0;
stringHolder = "";
// createSubstring(newString); // ?
}
}
}
我试过这个,但到目前为止没有运气。我什至尝试递归地做到这一点。我对 Javascript 有点陌生(实际上是为 Extendscript 做的),我认为有一种更简单的方法,可以使用,split/slice
但我还没有找到。我试图让它尽可能简单和快速地阅读,如果我能提供任何进一步的信息,请告诉我,提前谢谢!
解决方案
以下是如何使用split
.
var input = "255,255,255,10,251,91,31,4,220,220,220,1";
var inputArray = input.split(",");
var outputArray = [];
for(let i = 0;i<inputArray.length;i++)
{
if(i%4 != 3)
{
outputArray.push(inputArray[i]);
}
}
var output = outputArray.join(",");
console.log(output);
推荐阅读
- java - 在返回 Android 之前等待所有结果
- android - 如何在 Android 中使用 pySerial 查找 USB 设备并与之通信?
- r - 用于在 R 中创建用于网络分析的多个图的循环或向量
- javascript - 无法使用道具加载组件
- javascript - 锁定 Google Apps 脚本执行,直到文本被替换
- git - 如何在不签出该分支的情况下将最新代码拉到不同的分支?
- python - NameError:未定义名称“self”时引发错误
- bash - ChromeDriver 重新安装后停止工作。以前工作正常 - 没有进行其他更改。(苹果系统)
- javascript - clearTimeout 不能使用 jQuery 工作?
- javascript - 使用 html2canvas 呈现所有 div 时如何保存执行回调/操作