Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

294
Visualizações
¿Cómo puedo obtener un elemento aleatorio de varias matrices en función de una casilla de verificación?

Solo quiero mostrar el texto de las matrices que están seleccionadas con las casillas de verificación (por lo tanto, si solo quiero txt y ejecuté , solo muestra las opciones de esas matrices)

 function myFunc() { let txt = ["txt1", "txt2", "txt3"]; let test = ["test1", "test2", "test3"]; let ran = ["ran1", "ran2", "ran3"]; let tst = txt[Math.floor(Math.random() * txt.length)] + "<br><br><br>" + test[Math.floor(Math.random() * test.length)] + "<br><br><br>" + ran[Math.floor(Math.random() * ran.length)]; document.getElementById("tst").innerHTML = tst; }
 <input type="checkbox"> txt<br> <input type="checkbox"> test<br> <input type="checkbox"> ran <br> <br> <button onclick="myFunc()">One Character</button> <p id="tst"> sum text lol </p>

Código: https://jsfiddle.net/RoseLovesGreene/ps17u8yd/6/

También me gustaría poder mostrarlo en un orden aleatorio para que cada matriz no tenga su propia línea.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Puede usar una cláusula if para determinar si la casilla de verificación está marcada o no. Luego, si está marcado, use el número aleatorio como clave para la matriz, que luego puede agregar al resultado.

 function myFunc() { let txt = ["txt1", "txt2", "txt3"]; let test = ["test1", "test2", "test3"]; let ran = ["ran1", "ran2", "ran3"]; let target = document.getElementById('tst'); let result = ""; let txtKey = [Math.floor(Math.random() * txt.length)] let testKey = [Math.floor(Math.random() * test.length)] let ranKey = [Math.floor(Math.random() * ran.length)] if (document.getElementById('txt').checked) { result = result+txt[txtKey]; } if (document.getElementById('test').checked) { result = result+test[testKey]; } if (document.getElementById('ran').checked) { result = result+ran[ranKey]; } target.innerHTML = result; }
 <input id="txt" type="checkbox"> <label for="txt">txt</label><br> <input id="test" type="checkbox"> <label for="test">test</label><br> <input id="ran" type="checkbox"> <label for="ran">ran</label> <br> <br> <button onclick="myFunc()">One Character</button> <p id="tst"> sum text lol </p>

Hay algunas cosas que podrías hacer para que esto sea más elegante, pero creo que la idea funciona.

about 4 years ago · Juan Pablo Isaza Relatório

0

Para obtener los valores de sus casillas de verificación, debe darles value reales s, y para hacer referencia a las matrices sin un montón de declaraciones IF, deben ser referenciables en algo como un objeto.

Esto obtendrá valores aleatorios de cada matriz a medida que recorre forEach , pero la salida final debe barajarse (según sus especificaciones). Hay muchas maneras de hacer esto: tomé una de las versiones más concisas, pero hay muchas para elegir aquí: ¿Cómo aleatorizar (barajar) una matriz de JavaScript?

 function shuffle(a, b, c, d) { //array,placeholder,placeholder,placeholder c = a.length; while (c) b = Math.random() * (--c + 1) | 0, d = a[c], a[c] = a[b], a[b] = d; return a } function myFunc() { let vars = { txt: ["txt1", "txt2", "txt3"], test: ["test1", "test2", "test3"], ran: ["ran1", "ran2", "ran3"] } // get the checked values into an array let flatArr = []; document.querySelectorAll('[type=checkbox]:checked').forEach(el => { flatArr = [...flatArr, vars[el.value][Math.floor(Math.random() * vars[el.value].length)]] }); document.getElementById("tst").innerHTML = shuffle(flatArr).join(" "); }
 <input type="checkbox" value='txt'> txt<br> <input type="checkbox" value='test'> test<br> <input type="checkbox" value='ran'> ran <br> <br> <button onclick="myFunc()">One Character</button> <p id="tst"> sum text lol </p>

about 4 years ago · Juan Pablo Isaza Relatório

0

 //Object of arrays let options = { txt : ["txt1", "txt2", "txt3"], test : ["test1", "test2", "test3"], ran : ["ran1", "ran2", "ran3"] }; function myFunc() { //Get all checkboxes let checkedBoxes = document.querySelectorAll('input[type=checkbox]:checked'); //array for texts from arrays let texts = []; //loop through selected checkboxes checkedBoxes.forEach(function(ele) { // select respective array from object based on checkbox value let cOpt = options[ele.value]; // random index for texts array - to randomize array text line let index = Math.floor(Math.random() * checkedBoxes.length); // to make sure we didn't set a text to that index already while( texts[index] !== undefined ) { index = Math.floor(Math.random() * checkedBoxes.length); } // set selected array text to a random index in texts array texts[index] = cOpt[Math.floor(Math.random() * cOpt.length)]; }); // text.join() to covert texts array into string document.getElementById("tst").innerHTML = texts.join('<br><br>'); }
 <input type="checkbox" value="txt"> txt<br> <input type="checkbox" value="test"> test<br> <input type="checkbox" value="ran"> ran<br> <button onclick="myFunc()">One Character</button> <p id="tst"> sum text lol </p>

Necesita hacer algunos ajustes en su enfoque. es decir, establezca valores en las casillas de verificación, cree un js obj con todas las matrices siendo su propiedad.

Asegúrese de que los valores de las casillas de verificación y las claves de propiedades sean los mismos.

He agregado comentarios en el código para que pueda comprender fácilmente el propósito de cada línea.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda