// Task 1 /* - Напишите генератор массивов длиной count со случайными числами от n до m. Учтите, что n и m могут быть отрицательными, а также может быть n > m или n < m. - Выведите результат с помощью console.log. */ let array = []; // let n = 20; // let m = 10; // let count = 100; // let n = 2; // let m = 5; // let count = 50; // let n = 100; // let m = -5; // let count = 70; let n = -3; let m = -10; let count = 42; let range = Math.abs(m - n); let min = Math.min(n, m); for (let i = 0; i < count; i++) { array.push(Math.round(Math.random() * range) + min); } console.log(array); // Task 2 /* - Создайте с помощью цикла for массив упорядоченных чисел с количеством чисел, равным count. Например: - count = 5; соответствует массив [1,2,3,4,5]; - count = 7; соответствует массив [1,2,3,4,5,6,7]; - count = 3; соответствует массив [1,2,3]. - С помощью второго цикла перемешайте этот массив. - Выведите получившийся результат на экран с помощью console.log. */ let array1 = []; // let count1 = 3; let count1 = 5; // let count1 = 7; for (i = 1; i <= count1; i++) { array1.push(i); } for (i = 0; i < array1.length; i++) { let j = Math.round(Math.random() * i); let temp = array1[i]; array1[i] = array1[j]; array1[j] = temp; } console.log(array1); // task 3 /* - С помощью цикла найдите индекс (порядковый номер) элемента массива из предыдущего задания с числом n. Если такой элемент не будет найден, то выведите соответствующее сообщение на экран. - n = 1 - n = 3 - n = 7 */ // let n1 = 1; // let n1 = 3; let n1 = 7; // for (i of array1) { // if (i === n1) { // console.log(array1.indexOf(i)); // break; // } // } // if (i != n1) { // console.log("No index!"); // } let index = 0; for (i of array1) { if (i === n1) { index = array1.indexOf(i); console.log(index); break; } } if (index === 0) { console.log("No Element!"); } // task 4 /* Даны два массива: arr1 = [2, 2, 17, 21, 45, 12, 54, 31, 53]; arr2 = [12, 44, 23, 5]; - Напишите программу, которая будет объединять два массива: arr1 и arr2. - нужно вывести в консоль с помощью команды console.log в таком виде: [2, 2, 17, 21, 45, 12, 54, 31, 53, 12, 44, 23, 5] Важно: для выполнения этого задания можно использовать только один цикл. Программа должна корректно работать с массивами любой длины. Нельзя переприсвоить массивы целиком друг в друга */ let arr1 = [2, 2, 17, 21, 45, 12, 54, 31, 53]; let arr2 = [12, 44, 23, 5]; let arr = []; // for (el of arr2) { // arr1.push(el); // } for (i = 0; i < arr2.length; i++) { arr1.push(i); } console.log(arr1);
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.
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.
var readline = require('readline');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
rl.on('line', function(line){
console.log("Hello, " + line);
});
Keyword | Description | Scope |
---|---|---|
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 |
let greetings = `Hello ${name}`
const msg = `
hello
world!
`
An array is a collection of items or values.
let arrayName = [value1, value2,..etc];
// or
let arrayName = new Array("value1","value2",..etc);
let mobiles = ["iPhone", "Samsung", "Pixel"];
// accessing an array
console.log(mobiles[0]);
// changing an array element
mobiles[3] = "Nokia";
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.
() => expression
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);
let [firstName, lastName] = ['Foo', 'Bar']
let {firstName, lastName} = {
firstName: 'Foo',
lastName: 'Bar'
}
const {
title,
firstName,
lastName,
...rest
} = record;
//Object spread
const post = {
...options,
type: "new"
}
//array spread
const users = [
...adminUsers,
...normalUsers
]
function greetings({ name = 'Foo' } = {}) { //Defaulting name to Foo
console.log(`Hello ${name}!`);
}
greet() // Hello Foo
greet({ name: 'Bar' }) // Hi Bar
IF is used to execute a block of code based on a condition.
if(condition){
// code
}
Else part is used to execute the block of code when the condition fails.
if(condition){
// code
} else {
// code
}
Switch is used to replace nested If-Else statements.
switch(condition){
case 'value1' :
//code
[break;]
case 'value2' :
//code
[break;]
.......
default :
//code
[break;]
}
For loop is used to iterate a set of statements based on a condition.
for(Initialization; Condition; Increment/decrement){
//code
}
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
}
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);
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.
class className {
constructor() { ... } //Mandatory Class method
method1() { ... }
method2() { ... }
...
}
class Mobile {
constructor(model) {
this.name = model;
}
}
mbl = new Mobile("iPhone");