【问题标题】:How to take certain parts in one array and convert them into another character in javascript如何在一个数组中获取某些部分并将它们转换为javascript中的另一个字符
【发布时间】:2016-07-18 13:10:12
【问题描述】:

我创建了一个代码,它将颜色 red 识别为“on”,颜色 blue 识别为“off”,然后这些 on'soff's “推入”到一个名为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 变成破折号 (_) 和点 (.) 和 .pushanother 数组名为 senseMake,如果可能的话。

规则是:

  • 开启 1–2 个时间单位 = 点
  • 开启 ≥ 3 个时间单位 = 短跑

尝试创建 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);

【问题讨论】:

  • 请将您尝试的循环添加到您的问题中。
  • 请为这个特定的“on”/“off”数组添加您想要的结果。

标签: javascript arrays mobile-application


【解决方案1】:

这是一个使用正则表达式的有效解决方案(无迭代)。整个事情可能是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('');

但我在 sn-p 中将其分成多行以便于理解。

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; }

希望这会有所帮助!

【讨论】:

  • 如果 on's 和 off's 不断地添加到数组中,是否一样只需创建一个新变量,例如 var array = initial
  • 我不确定你的意思,你能改写这个问题吗?...顺便说一句,我已经编辑了我的答案以反映你的预期结果。它现在生成一个看起来像 [ "_", "_", "." ] 的数组
  • 由于数组不是静态的,因此根据颜色是红色还是蓝色添加“on”和“off”。因此:var initial = ['on', 'on', 'on', 'off', 'off', 'off', 'on', 'on', 'on', 'off', 'on', 'off']; 只能在它是一个集合数组时使用,这意味着您确切知道它们的顺序。有没有办法说初始不等于集合数组?
  • 无论数组中的开关顺序如何,我的代码都可以工作。所以只要没有像“quantum”这样的奇怪字符串被添加到数组中,你应该没问题:)
猜你喜欢
  • 2018-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多