2015-08-27 25 views
0

У меня есть сценарий, созданный для захвата цитаты из массива наугад и отображения его.Разбить строку в JS

Я пытаюсь форматировать его, чтобы он расколет цитаты и автор, как так:

«Вставить цитату»
Имя человека говорят Цитата

Я попытался с помощью раскола с \n и <br />, и ничего не работает, даже в тревоге.

вот мой код:

//Initalize the array 
var quotes = []; 

//Insert data into the array 
quotes[0] = "It doesn't matter how many times you have failed, you only have    to be right once." + "Mark Cuban"; 
quotes[1] = "Video games are bad for you? That's what they said about rock n' roll." + "Shigeru Miyamoto"; 
quotes[2] = "I'd like to be known as the person who saw things from a       different point of view to others." + "Shigeru Miyamoto"; 
quotes[3] = "Stay hungry, stay foolish, stay crazy." + "Steve Jobs"; 
quotes[4] = "The future was uncertain, absolutely, and there were many hurdles, twists, and turns to come, but as long as I kept moving forward, one foot in front of the other, the voices of fear and shame, the messages from those who wanted me to believe that I wasn't good enough, would be stilled." + "Chris Gardner"; 
quotes[5] = "Running a start-up is like eating glass. You just start to like the taste of your own blood." + "Sean Parker"; 
quotes[6] = "I used to drink cristal, the muh'fucker's racist. So I switched gold bottles on to that Spade shit" + "Shawn Carter (Jay Z)"; 
quotes[7] = "I think it's better to let my work do the talking" + "Shigeru Miyamoto."; 
quotes[8] = "Success is a lousy teacher. It seduces smart people into thinking they can't lose." + "Bill Gates"; 
quotes[9] = "We need to reengineer companies to focus on figuring out who the customer is, what's the market and what kind of product you should build." + "Eric Ries"; 
quotes[10] = "I have no friends and no enemies - only competitors." + "Aristole Onassis"; 
quotes[11] = "Working 24 hours a day isn't enough anymore. You have to be willing to sacrifice everything to be successful, including your personal life, your family life, maybe more. If people think it's any less, they're wrong, and they will fail." + "Kevin O'Leary"; 
quotes[12] = "My hope is to the see the benefits of my labour spread out in the community." + "W. Brett Wilson"; 
quotes[13] = "I'm not here to make friends; I'm here to make money." + "Kevin O'Leary"; 
quotes[14] = "Good artists copy, great artists steal" + "Pablo Picasso"; 
quotes[15] = "Welcome ladies and gentlemen to the eighth wonder of the world. The flow of the century, always timeless; HOV!" + "Shawn Carter (Jay Z)"; 
quotes[16] = "Today’s “best practices” lead to dead ends; the best paths are new and untried." + "Peter Thiel"; 
quotes[17] = "I believe life is an intelligent thing: that things aren't random." + "Steve Jobs"; 
quotes[18] = "Pretty? You mean like rainbows, unicorns, and sparkles?" + "Michelle Brown"; 
quotes[19] = ".....and for that reason, I'm OUT!" + "Mark Cuban"; 

//Splits the quote into two pieces, the quote and the person. 

var quoteSplit = function (quotes) { 
    var split = quotes.split("+").replace("\n"); 
} 

//Displays a quote from the array at random. 

var displayQuote = quotes[Math.floor(20 * Math.random())]; 
document.write(displayQuote); 

//END 
+4

Можно ли изменить структуру вашего массива? Вы можете создавать объекты с свойствами «quote» и «author». – showdev

+7

'+' не входит в вашу строку - ее часть кода. –

+0

@ DanielA.White просто дал вам ответ. – Onilol

ответ

3

Когда вы создаете свой массив, вы конкатенации цитаты с автором. Так что это:

quotes[0] = "It doesn't matter how many times you have failed, you only have to be right once." + "Mark Cuban"; 

Заканчивается с этим строка, в которой установлена ​​quotes[0]

It doesn't matter how many times you have failed, you only have to be right once.Mark Cuban 

И разделенное заявление не будет работать, потому что + не входят в строке. Однако это не отличный способ настроить ваш массив. Что произойдет, если ваша цитата содержит, например, символ +?

Лучше всего было бы создать объект для каждого элемента:

quotes[0] = { 
    text: "It doesn't matter how many times you have failed, you only have to be right once.", 
    author: "Mark Cuban" 
} 

Тогда вы можете сделать:

var displayQuote = quotes[Math.floor(20 * Math.random())]; 
document.write(displayQuote.text + '<br>' + displayQuote.author); 
+0

Ты избил меня. Наличие объектов будет очень простым, и нет необходимости выполнять дополнительные операции над строками. –

0

Это кажется, что + знак не в строке. Следующий код:

console.log("Today’s “best practices” lead to dead ends; the best paths are new and untried." + "Peter Thiel"); 

вернется к вам строке

«наилучшей практики» Сегодняшней привести к тупикам; лучшие пути - новые и неопытные. Питер Тиэль;

Таким образом, вы просто должны включать + сиговых в ваших строк так:

"Today’s “best practices” lead to dead ends; the best paths are new and untried.+Peter Thiel" 
0

Как Даниэль А. Белый сказал в разделе комментариев. Вы рассматриваете +, чтобы быть частью строки, но на самом деле вы объединяете 2 строки по каждому индексу.

quotes[3] = "Stay hungry, stay foolish, stay crazy." + "Steve Jobs"; 

должен быть:

quotes[3] = "Stay hungry, stay foolish, stay crazy.+Steve Jobs"; 

Или вы можете использовать регулярные выражения (К сожалению, я не могу обеспечить регулярное выражение примера прямо сейчас), но те два из ваших возможных вариантов.

0

Если вы выведете любой элемент вашего массива, вы увидите, что каждая запись представляет собой одну строку с цитатой и человеком. Ex.

console.log(quotes[3]); 
Stay hungry, stay foolish, stay crazy.Steve Jobs 

Это потому, что + объединяется при применении к строкам.

Как было предложено в комментариях, вы можете использовать разделение на знаки препинания, хотя это сломало бы некоторые ваши кавычки.

Вы могли бы сделать что-то вроде

quotes[3]=["Stay hungry, stay foolish, stay crazy.","Steve Jobs"]; 

и выход каждого элемента в отдельности.

0

Попробуйте это:

var quotes = { 
    1: { 
    quote: 'Hello world.', 
    author: 'Test test' 
    }, 
    2: { 
    quote: 'Hello world 2.', 
    author: 'Test test 2' 
    }, 
}; 

// Display random quote 
function displayQuote(){ 
    var key = Math.floor(Math.random() * Object.keys(quotes).length + 1); 
    return quotes[key].quote + ' ' + quotes[key].author; 
}; 

document.write(displayQuote()); 
Смежные вопросы