Циклическое перемешивание абзацев с помощью нажатия кнопкиJavascript

Форум по Javascript
Ответить
Anonymous
 Циклическое перемешивание абзацев с помощью нажатия кнопки

Сообщение Anonymous »

Я новичок в JavaScript и изо всех сил стараюсь создать небольшую программу, которая перемешивает слова в абзаце. У меня перемешивание работает для одного абзаца (спасибо множеству полезных фрагментов кода и полезному другу-программисту!), но теперь я не уверен, как перебирать все остальные абзацы, когда пользователь нажимает кнопку "Перемешать меня".
Каждый щелчок должен вызвать случайный абзац, перетасовать его, а затем вывести его в поле.
Я ожидаю, что мне нужно создать функцию, которая присваивает случайный абзац номер для каждого предложения, который затем можно использовать внутри тасования. У меня в голове есть идея, как заставить ее работать, но у меня нет знаний Javascript, чтобы реализовать ее на практике. Если кто-нибудь будет достаточно любезен, чтобы помочь мне, я буду очень признателен! Вот мой код ниже:




shuffle me



var sentence = 'You will rejoice to hear that no disaster has accompanied the commencement of an enterprise which you have regarded with such evil forebodings. I arrived here yesterday, and my first task is to assure my dear sister of my welfare and increasing confidence in the success of my undertaking.'

var sentence2 = 'Call me Ishmael. Some years ago—never mind how long precisely—having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world. It is a way I have of driving off the spleen and regulating the circulation.'

var sentence3 = 'It is a truth universally acknowledged, that a single man in possession of a good fortune must be in want of a wife. However little known the feelings or views of such a man may be on his first entering a neighbourhood, this truth is so well fixed in the minds of the surrounding families, that he is considered as the rightful property of some one or other of their daughters.'

/* I'm thinking I need something like this below?

function sentenceSelect() {
generate random number 1 - 3
case 1:
return sentence1
case 2:
return sentence2
case 3:
return sentence3
}
var sentence = sentenceSelect();

*/

// Shuffle function for arrays
Array.prototype.shuffle = function() {
var i = this.length;
if (i == 0) return this;
while (--i) {
var j = Math.floor(Math.random() * (i + 1));
var a = this;
var b = this[j];
this = b;
this[j] = a;
}
return this;
};

function scramble() {
// Shuffle the sentence words
var shuffledSentence = sentence.split(' ').shuffle().slice(0, 10).join(' ');
// Display the shuffled sentence on the webpage
document.getElementById('output').innerHTML = shuffledSentence;
return;
}

scramble();





Подробнее здесь: https://stackoverflow.com/questions/797 ... on-onclick
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»