I have a problem with showing values on the screen with javascript

3

I'm just starting with this language, but when I want to show some value I do not see anything, any solution?

HTML code

<html>
    <head>
        <title>Arreglos</title>
    </head>

    <body>
        <script src="arreglos.js"></script>
    </body>
</html>

Javascript code

var amigos = {"Ana", "Juan", "Ismael"};
document.write(amigos[0]);
    
asked by Fernando 23.03.2018 в 00:10
source

3 answers

2

You are confusing the object with an array:

> var amigos = {"Ana", "Juan", "Ismael"}
Uncaught SyntaxError: Unexpected token ,

It should be (brackets are used to create an array):

> var amigos = ["Ana", "Juan", "Ismael"]
> amigos[0]
"Ana"

With this clear, we try again:

// arreglos.js
var amigos = ["Ana", "Juan", "Ismael"]; 
document.write(amigos[0]);
<body>
    <script src="arreglos.js"></script>
</body>

Your friends:

// arreglos.js
var amigos = ["Ana", "Juan", "Ismael"]; 
document.write("Mis amigos son: " + amigos.join(', '));
<body>
    <script src="arreglos.js"></script>
</body>

It works!

    
answered by 23.03.2018 в 00:35
1

What you can do is JQuery to automatically show you the result

$( document ).ready(function() {
    var amigos = ["Ana", "Juan", "Ismael"];
    document.write(amigos[0]); 
});
<html>
    <head>
        <title>Arreglos</title>
    </head>

    <body>
        
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script src="arreglos.js"></script>
    </body>
</html>

In addition to misstating the array, change the brackets by brackets.

    
answered by 23.03.2018 в 00:25
1

Just to add, the join () method joins the elements of an array and returns a string, the elements are separated by a specific separator, the default separator is ",".

// arreglos.js
var amigos = ["Ana", "Juan", "Ismael"]; 
document.write("Mis amigos son: " + amigos.join(', '));
<body>
    <script src="arreglos.js"></script>
</body>
    
answered by 23.03.2018 в 16:41