Question when multiple javascript variables are entered

Asked 1 years ago, Updated 1 years ago, 51 views

You want to receive multiple inputs as a prompt and save them in a variable. vara,b = prompt ("Enter two numbers: ").split(" "); When I wrote it, it only went into b.
Python used to have good variables even if it was written like that. How can I put the split("") value in a and b in JavaScript?

javascript input

2022-09-21 15:38

2 Answers

Hello! This is how you do it

var [a, b] = prompt ("Enter two numbers: ").split(" ")

In Python, it's called Tuple Destruction.

(a, b) = [1, 2]

Each extraction from the array goes through a tuple distrctoring process, since parentheses can be omitted in Python

a, b = [1, 2]

I used it like this :)

JavaScript also has Array Destruction and Object Destruction in this way

//Array Destructuring
var foo = ['one', 'two', 'three']
var [one, two, three] = foo
console.log(one)

//Object Destructuring 
var o = {p: 42, q: true}
var {p, q} = o
console.log(p)
console.log(q)

Have a nice day to day!


2022-09-21 15:38

// This code is
vara, b = prompt ("Enter two numbers : ").split(" ");

// It's like this
var a;
var = prompt ("Enter two numbers : ").split(" ");

// It's different from this.
vara = prompt ("Enter two numbers : ").split(" ");
var = prompt ("Enter two numbers : ").split(" ");

// So a contains nothing.
console.log(a) // >> undefined
// split() returns an array.
var = prompt ("Enter two numbers : ").split(" ");
console.log(b); // >> [99, 87]
console.log(b[0]) // >> 99
console.log(b[1]) // >> 87


2022-09-21 15:38

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.