Я новичок в 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
Циклическое перемешивание абзацев с помощью нажатия кнопки ⇐ Javascript
Форум по Javascript
-
Anonymous
1760831099
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[i];
var b = this[j];
this[i] = 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();
Подробнее здесь: [url]https://stackoverflow.com/questions/79794017/cycle-shuffled-paragraphs-with-button-onclick[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия