How to print an array vertically in javascript

I have a javascript array where, for each iteration, a name is added to the end using the push feature. I'm sending this array to a html file where it will be displayed. Currently displaying this array after all iterations have completed gives:

John, Smith, Paul, Doe

However, I wish the array to be displayed vertically like:

John
Smith
Paul
Doe

In Javascript, is there some way to specify for each name to be entered as a new row in the array? In Matlab you can easily specify which row or column you want data to be stored in the array but I am yet to find a simple approach in Javascript.

Thank you for any help you might be able to give me!

UPDATE: Javascript [simplified]:

port.onMessage.addListener[function[msg] {
    var Array = []
    var Names = ["John", "Smith", "Paul", "Doe"]
    for [var p = 0; p < Names.length; p++] {
    Array.push[Names[p]]
    }
    document.getElementById['status'].textContent = Array;
}];

HTML [simplified]:


    
    
        
            body { 
                min-width       : 400px;
                min-height      : 300px;
                text-align      : right;
                background-color: #D0D0D0; }
            #status { 
                font-size       : 10px;
                color           : #0000CC;
                text-align      : left;
                font-family     : "Times New Roman", Times, serif; }
        
    
    
    

Last update on August 19 2022 21:51:52 [UTC/GMT +8 hours]

JavaScript Array: Exercise-10 with Solution

Write a JavaScript program which prints the elements of the following array.

Note : Use nested for loops.
Sample array : var a = [[1, 2, 1, 24], [8, 11, 9, 4], [7, 0, 7, 27], [7, 4, 28, 14], [3, 10, 26, 7]];
Sample Output :
"row 0"
" 1"
" 2"
" 1"
" 24"
"row 1"
------
------

Pictorial Presentation:

Sample Solution:

HTML Code:





Print 2-D array





JavaScript Code:

// a sample 2-D array 
var a = [[1, 2, 1, 24], [8, 11, 9, 4], [7, 0, 7, 27], [7, 4, 28, 14], [3, 10, 26, 7]];
 
for [var i in a] 
{
   console.log["row " + i];
   for [var j in a[i]] 
     {
      console.log[" " + a[i][j]];
     }
}

Sample Output:

row 0
 1
 2
 1
 24
row 1
 8
 11
 9
 4
row 2
 7
 0
 7
 27
row 3
 7
 4
 28
 14
row 4
 3
 10
 26
 7

Flowchart:

ES6 Version:

// a sample 2-D array 
const a = [[1, 2, 1, 24], [8, 11, 9, 4], [7, 0, 7, 27], [7, 4, 28, 14], [3, 10, 26, 7]];
 
for [const i in a] 
{
   console.log[`row ${i}`];
   for [const j in a[i]] 
     {
      console.log[` ${a[i][j]}`];
     }
}

Live Demo:

See the Pen JavaScript - Print the elements of an array- array-ex- 10 by w3resource [@w3resource] on CodePen.

Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program which accept a string as input and swap the case of each character.
Next: Write a JavaScript program to find the sum of squares of a numeric vector.

JavaScript: Tips of the Day

Eequality test

console.log[Number[2] === Number[2]];
console.log[Boolean[false] === Boolean[false]];
console.log[Symbol['foo'] === Symbol['foo']];

Every Symbol is entirely unique. The purpose of the argument passed to the Symbol is to give the Symbol a description. The value of the Symbol is not dependent on the passed argument. As we test equality, we are creating two entirely new symbols: the first Symbol['foo'], and the second Symbol['foo']. These two values are unique and not equal to each other, Symbol['foo'] === Symbol['foo'] returns false.

Ref: //bit.ly/323Y0P6

Javascript Online Compiler

Write, Run & Share Javascript code online using OneCompiler's JS online compiler for free. It's one of the robust, feature-rich online compilers for Javascript language. Getting started with the OneCompiler's Javascript editor is easy and fast. The editor shows sample boilerplate code when you choose language as Javascript and start coding.

About Javascript

Javascript[JS] is a object-oriented programming language which adhere to ECMA Script Standards. Javascript is required to design the behaviour of the web pages.

Key Features

  • Open-source
  • Just-in-time compiled language
  • Embedded along with HTML and makes web pages alive
  • Originally named as LiveScript.
  • Executable in both browser and server which has Javascript engines like V8[chrome], SpiderMonkey[Firefox] etc.

Syntax help

variable declaration

KeywordDescriptionScope
var Var is used to declare variables[old way of declaring variables] Function or global scope
let let is also used to declare variables[new way] Global or block Scope
const const is used to declare const values. Once the value is assigned, it can not be modified Global or block Scope

Backtick Strings

Interpolation

let greetings = `Hello ${name}`

Multi line Strings

const msg = `
hello
world!
`

Arrays

An array is a collection of items or values.

Syntax:

let arrayName = [value1, value2,..etc];
// or
let arrayName = new Array["value1","value2",..etc];

Example:

let mobiles = ["iPhone", "Samsung", "Pixel"];

// accessing an array
console.log[mobiles[0]];

// changing an array element
mobiles[3] = "Nokia";

Arrow functions

Arrow Functions helps developers to write code in concise way, it’s introduced in ES6.
Arrow functions can be written in multiple ways. Below are couple of ways to use arrow function but it can be written in many other ways as well.

Syntax:

[] => expression

Example:

const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
const squaresOfEvenNumbers = numbers.filter[ele => ele % 2 == 0]
                                    .map[ele => ele ** 2];
console.log[squaresOfEvenNumbers];

De-structuring

Arrays

let [firstName, lastName] = ['Foo', 'Bar']

Objects

let {firstName, lastName} = {
  firstName: 'Foo',
  lastName: 'Bar'
}

rest[...] operator

 const {
    title,
    firstName,
    lastName,
    ...rest
  } = record;

Spread[...] operator

//Object spread
const post = {
  ...options,
  type: "new"
}
//array spread
const users = [
  ...adminUsers,
  ...normalUsers
]

Functions

function greetings[{ name = 'Foo' } = {}] { //Defaulting name to Foo
  console.log[`Hello ${name}!`];
}
 
greet[] // Hello Foo
greet[{ name: 'Bar' }] // Hi Bar

Loops

1. If:

IF is used to execute a block of code based on a condition.

Syntax

if[condition]{
    // code
}

2. If-Else:

Else part is used to execute the block of code when the condition fails.

Syntax

if[condition]{
    // code
} else {
    // code
}

3. Switch:

Switch is used to replace nested If-Else statements.

Syntax

switch[condition]{
    case 'value1' :
        //code
        [break;]
    case 'value2' :
        //code
        [break;]
    .......
    default :
        //code
        [break;]
}

4. For

For loop is used to iterate a set of statements based on a condition.

for[Initialization; Condition; Increment/decrement]{  
//code  
} 

5. While

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while [condition] {  
  // code 
}  

6. Do-While

Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.

do {  
  // code 
} while [condition]; 

Classes

ES6 introduced classes along with OOPS concepts in JS. Class is similar to a function which you can think like kind of template which will get called when ever you initialize class.

Syntax:

class className {
  constructor[] { ... } //Mandatory Class method
  method1[] { ... }
  method2[] { ... }
  ...
}

Example:

class Mobile {
  constructor[model] {
    this.name = model;
  }
}

mbl = new Mobile["iPhone"];

How do you print an array in JavaScript?

We can print all array elements by passing the array's name to the console. log[] function. We can also use map[] and join[] methods to manipulate first and then print the array's elements. For instance, we want to number each array element in the output.

How do I print a horizontal number in JavaScript?

To Print 5 * Horizontally.
S = "".
for [i = 1; i

Chủ Đề