массивы javascript в Chrome и Internet Explorer - PullRequest
0 голосов
/ 14 мая 2011

У меня есть этот код, и он работал в Google Chrome, но он не работал в Internet Explorer.

<html><head>
 <script type ="text/JavaScript">
<!--
function status()
{
    var text = newArray();
    text[0] = "Life is traveled only once..Today's moment becomes tomorrow's memory..Enjoy every moment; good, bad, happy, or sad;because the gift of life is LIFE itself";
    text[1] = "never design your character like a garden where any one can walk. but design your character like the sky, where everyone likes to reach you";
    text[2] = "Crying is never a symbol of weakness... From the time we are born, it has always been a sign that we are alive...";
    text[3] = "If you believe, you can achieve!";
    text[4] = "BELIEVE: To hope for the best, endure the stress, passing every test & accepting nothing less.";
    text[5] = "Never give up on your dreams and goals, if you do,your life end up no where.";
    text[6] = "The only thing that is guaranteed forever is your family... they will always be your family.. everything else can change.";
    var i = Math.floor(7*Math.random())
    var g=window.alert(text[i]);
    return g ;
}
//-->
</script>
</head></html>

Ответы [ 5 ]

4 голосов
/ 14 мая 2011

newArray(); должно быть new Array(); или даже лучше, [].

Кроме того, вы не можете иметь разрывы строк внутри строк JavaScript - замените физические разрывы строк на \n.

Также нет смысла возвращать возвращаемое значение alert().

2 голосов
/ 14 мая 2011

Для такого рода вещей лучше всего использовать литерал массива:

var text = [
    "Life is traveled only once..Today's moment becomes tomorrow's memory..Enjoy every moment; good, bad, happy, or sad;because the gift of life is LIFE itself",
    "never design your character like a garden where any one can walk. but design your character like the sky, where everyone likes to reach you",
    "Crying is never a symbol of weakness... From the time we are born, it has always been a sign that we are alive...",
    "If you believe, you can achieve!",
    "BELIEVE: To hope for the best, endure the stress, passing every test & accepting nothing less.",
    "Never give up on your dreams and goals, if you do,your life end up no where.",
    "The only thing that is guaranteed forever is your family... they will always be your family.. everything else can change."
];

Это создаст новый массив с записями, которые вы перечислили. Записи массива разделяются запятыми. После последней записи запятых нет (если вы поместите одну из них туда, некоторые браузеры будут помещать постороннюю запись undefined в конец массива, потому что спецификация раньше была неопределенной; ее больше нет, но некоторые старые браузеры все еще имеют вопрос).

Я не помню, когда в последний раз мне приходилось писать var a = new Array() (обратите внимание на пробел). Даже для пустого массива используйте var a = [];. Он не только короче, но и исключает возможность затенения Array (символа).

0 голосов
/ 14 мая 2011

Я бы написал ваш код так:

var status = function() {
    var text = [
        "Life is traveled only once..Today's moment becomes tomorrow's memory..Enjoy every moment; good, bad, happy, or sad;because the gift of life is LIFE itself"
        , "never design your character like a garden where any one can walk. but design your character like the sky, where everyone likes to reach you"
        , "Crying is never a symbol of weakness... From the time we are born, it has always been a sign that we are alive..."
        , "If you believe, you can achieve!"
        , "BELIEVE: To hope for the best, endure the stress, passing every test & accepting nothing less."
        , "Never give up on your dreams and goals, if you do,your life end up no where."
        , "The only thing that is guaranteed forever is your family... they will always be your family.. everything else can change."
    ], i = Math.floor(7*Math.random());
    alert(text[i]);
}
0 голосов
/ 14 мая 2011

Правильный код: var text = new Array();

0 голосов
/ 14 мая 2011

Изменить строку

var g=window.alert(text[i]);

до

var g = text[i];
alert(g);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...