Cadena de ejemplo : astnbodei , la cadena real debe ser santobedi . Aquí, mi sistema comienza a leer un par de dos caracteres del lado izquierdo de una cadena, primero el LSB y luego el MSB del par de caracteres. Por lo tanto, santobedi se recibe como astnbodei . Las cadenas pueden ser una combinación de letras y números y longitudes de caracteres pares/impares.
Mi intento hasta ahora :
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(/\0/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 codeMientras ejecutaba el fragmento de código anterior, recibí el siguiente error:
No se puede compilar el script: javax.script.ScriptException: :36:14 Esperado: pero encontrado (return {__if(); ^ en la línea número 36 en la columna número 14
No estoy seguro de lo que dice el error. ¿Es correcto mi enfoque? ¿Hay una manera directa de hacerlo?
El intercambio de caracteres por pares consecutivos de / dentro de una cadena se puede resolver muy fácilmente mediante una tarea de 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") );¿Intentó recorrer la matriz en pares e intercambiar usando la sintaxis ES6?
Puede intercambiar variables como esta en ES6: [a, b] = [b, a]
A continuación se muestra una forma de hacerlo. El código que tiene no es válido porque no se permite la return fuera de una función.
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(''));