交换 JavaScript 中字符串的 consecutive/adjacent 个字符

Swapping consecutive/adjacent characters of a string in JavaScript

示例字符串astnbodei,实际字符串必须是santobedi。在这里,我的系统开始从字符串的左侧读取一对两个字符,首先是 LSB,然后是字符对的 MSB。因此,santobedi 被接收为 astnbodei。字符串可以是字母和数字的组合以及 even/odd 个字符长度。

我目前的尝试:

var attributes_ = [Name, Code,
    Firmware, Serial_Number, Label
]; //the elements of 'attributes' are the strings
var attributes = [];

for (var i = 0; i < attributes_.length; i++) {
    attributes.push(swap(attributes_[i].replace(/[=12=]/g, '').split('')));
}

function swap(array_attributes) {
    var tmpArr = array_attributes;
    for (var k = 0; k < tmpArr.length; k += 2) {
        do {
            var tmp = tmpArr[k];
            tmpArr[k] = tmpArr[k+1]
            tmpArr[k+1] = tmp;
        } while (tmpArr[k + 2] != null);
    }
    return tmpArr;
}

msg.Name = attributes; //its to check the code

return {msg: msg, metadata: metadata,msgType: msgType}; //its the part of system code

在 运行 以上代码段中,我收到以下错误:

无法编译脚本:javax.script.ScriptException: :36:14 预期:但发现(return {__if(); ^ 在第 36 行第 14 列

我不确定错误是什么意思。我的方法正确吗?有直接的方法吗?

您是否尝试过成对遍历数组并使用 ES6 语法进行交换?

你可以在 ES6 中像这样交换变量: [a, b] = [b, a]

下面是一种方法。您的代码无效,因为函数外不允许 return

let string = "astnbodei";
let myArray = string.split('');
let outputArray = [];

for (i=0; i<myArray.length; i=i+2) {
    outputArray.push(myArray[i+1]);
  outputArray.push(myArray[i]);
}

console.log(outputArray.join(''));

题目出错的原因是函数swap的位置。然而,切换它的位置给了我另一个错误:

java.util.concurrent.ExecutionException: java.util.concurrent.ExecutionException: javax.script.ScriptException: delight.nashornsandbox.exceptions.ScriptCPUAbuseException: Script used more than the allowed [8000 ms] of CPU time.

@dikuw 的回答部分帮助了我。以下代码行对我有用:

var attributes_ = [Name, Code,
    Firmware, Serial_Number, Label
]; //the elements of 'attributes' are the strings
var attributes = [];

for (var i = 0; i < attributes_.length; i++) {
    attributes.push(swap(attributes_[i].replace(/[=10=]/g, '').split('')));
}

return {msg: msg, metadata: metadata,msgType: msgType};

function swap(array_attributes) {
    var tmpArr = [];
    for (var k = 0; k < array_attributes.length; k= k+2) {
        if( (array_attributes[k + 1] != null)) {
            tmpArr.push(array_attributes[k+1]);
            tmpArr.push(array_attributes[k]);
    }}
    return tmpArr.join('');
}

连续成对字符交换of/within一个字符串很容易通过reduce任务解决...

function swapCharsPairwise(value) {
  return String(value)
    .split('')
    .reduce((result, antecedent, idx, arr) => {
      if (idx % 2 === 0) {

        // access the Adjacent (the Antecedent's next following char).
        adjacent = arr[idx + 1];

        // aggregate result while swapping `antecedent` and `adjacent`.
        result.push(adjacent, antecedent);
      }
      return result;
    }, []).join('');
}
console.log(
  'swapCharsPairwise("astnbodei") ...',
  swapCharsPairwise("astnbodei")
);