JS分裂变量

问题描述 投票:1回答:4

我有一个像“iyxnhel2jeh”的字符串,我希望每2个字节我想将它们分成单个var。

var string = "iyxnhel2jehe";
var final = "";

while (/*String still has bits*/) {
    switch (/*Two byte of string*/) {
        case "iy":
            final += "x";
        break;
        case "xn":
            final += "o";
        break;
        case "he":
            final += "g";
        break;
        case "l2":
            final += "k";
        break;
        case "je":
            final += "e";
        break;
        default:
            final += "none"
    }
}

什么是削减这个字符串的最佳方法?

javascript string while-loop switch-statement
4个回答
3
投票

您可以使用正则表达式将字符串拆分为2个部分,将它们映射到switch语句中的字符并将数组连接在一起,但是最好的方法是删除switch语句,而是使用这些字符序列作为键一个对象。

var string = "iyxnhel2jehe";
var final = string.match(/.{1,2}/g).map(twoletters => {
    return {
        "iy": "x",
        "xn": "o",
        "he": "g",
        "l2": "k",
        "je": "e"
    }[twoletters] || "none";
}).join("");
console.log(final)

3
投票

我不确定最好的方法,但以下会做你想要的......

var string = "iyxnhel2jehe";
var final = "";

for (var i = 0; i < string.length; i+=2) {
  switch (string.substr(i,2)) {
        case "iy":
            final += "x";
        break;
        case "xn":
            final += "o";
        break;
        case "he":
            final += "g";
        break;
        case "l2":
            final += "k";
        break;
        case "je":
            final += "e";
        break;
        default:
            final += "none"
   }
}
console.log(final);

1
投票

var string = "iyxnhel2jehe";
var final = "";
var offset = 0;
while (offset < string.length) {
	switch (string.slice(offset, offset + 2)) {
		case "iy":
			final += "x";
			break;
		case "xn":
			final += "o";
			break;
		case "he":
			final += "g";
			break;
		case "l2":
			final += "k";
			break;
		case "je":
			final += "e";
			break;
		default:
			final += "none"
	}
	offset += 2;
}
console.log(final);

1
投票

不要尝试使用字符并检查是否还有剩余字符,而是先尝试将字符串拆分为2个字符的块,然后循环遍历数组:

const s = "iyxnhel2jehe";
let final = "";

const t = s.split('');
const segments = t.map((e, i) => i % 2 === 0 ?
                                 e + (t.length - 1 >= i + 1 ? t[i + 1] : '') :
                                 null)
                  .filter(x => x != null);

segments.forEach(sg => {
    console.log(sg);
    switch (sg) {
        case "iy":
            final += "x";
        break;
        case "xn":
            final += "o";
        break;
        case "he":
            final += "g";
        break;
        case "l2":
            final += "k";
        break;
        case "je":
            final += "e";
        break;
        default:
            final += "none"
    }
});

console.log(final);
© www.soinside.com 2019 - 2024. All rights reserved.