gpt4 book ai didi

javascript - 如何在一个数组中获取某些部分并将它们转换为javascript中的另一个字符

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

我创建了一个识别颜色 red 的代码作为“开”和颜色blue作为“关闭”,这些打开关闭然后被“推”到一个名为initial的空数组中,这可以在下面看到。

if (red > blue){
initial.push("on");
console.log(initital);
console.log(initial.length);
return true;
}

else {
initial.push("off");
console.log(initial);
console.log(initial.length);
return false;

}

当它运行并显示如下输出时:

[on, on, on, off, off, off, on, on, on, off, off, off, on]

但我需要将这些on'soff's 变成破折号(_)和点(.)和.push它们在名为 senseMake另一个 数组中,如果可能的话。

规则是:

  • 点亮 1-2 个时间单位 = 点
  • 开启 ≥ 3 个时间单位 = Dash

尝试创建一个 for 循环但不起作用,请帮忙。

所以上面数组的结果应该是: [_, ,_, ,.]

我使用的循环是

for (i=0; i<initial.length; i += 2)
senseMake.push(".");
console.log(senseMake);

for (i=0; i<initial.length; i += 3)
senseMake.push("_");
console.log(senseMake);

最佳答案

这是一个使用正则表达式的高效解决方案(无迭代)。整个事情可能在 2 行左右,即:

var initial = ['on', 'on', 'on', 'off', 'off', 'off', 'on', 'on', 'on', 'off', 'on', 'off'];
var senseMake = initial.join('').replace(/(on){3,}/gi, '_').replace(/(on){1,2}/gi, '.').replace(/off/gi, '').split('');

但我在代码片段中将其分成多行以使其更易于理解。

var initial = ['on', 'on', 'on', 'off', 'off', 'off', 'on', 'on', 'on', 'off', 'on', 'off'];
var senseMake = initial.join(''); // join the elements of the array into a string
senseMake = senseMake.replace(/(on){3,}/gi, '_'); // replace every instance of 3+ 'ons' with a _
senseMake = senseMake.replace(/(on){1,2}/gi, '.'); // replace every instance of 1-2 'ons' with a .
senseMake = senseMake.replace(/off/gi, ''); // replace every instance of 'off' with an empty string
senseMake = senseMake.split(''); // split every character into the elements of an array
document.write(JSON.stringify(senseMake, null, ' ')); // display result in window
* { font-family: monospace; }

希望这对您有所帮助!

关于javascript - 如何在一个数组中获取某些部分并将它们转换为javascript中的另一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36310393/

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