Напишите сценарий который обменивает местами значения двух введенных переменных javascript

Нужно поменять местами два введённых значения. Не могу понять, где ошибка, что onBlur не срабатывает. function replaceValues(obj) { var buffer = obj.valueAlpha.value; obj.valueAlpha.value ...

Нужно поменять местами два введённых значения. Не могу понять, где ошибка, что onBlur не срабатывает.

function replaceValues(obj)
{
	var buffer = obj.valueAlpha.value;
	obj.valueAlpha.value = obj.valueBeta.value;
	obj.valueBeta.value= buffer;
}
<FORM name="form" onblur="replaceValues(form)">
<input type="text" size=7 name="valueAlpha">
<input type="text" size=7 name="valueBeta">
</FORM>

задан 1 дек 2018 в 12:29

ti-phonex's user avatar

У события onblur нет фазы всплытия (как и у onfocus). Поэтому, Вы не можете отловить его с помощью делегирования, как в вашем примере.

Используйте события onfocusout и onfocusin, для достижения цели:

onBlur срабатывает только на том элементе, где произошло событие. Поэтому, нужно прописывать такой обработчик каждому элементу:

ответ дан 1 дек 2018 в 13:14

UModeL's user avatar

UModeLUModeL

30k5 золотых знаков27 серебряных знаков65 бронзовых знаков

2

Упражнения

1.
Вводится информация о доходах сотрудника
за первый квартал текущего года. Требуется
определить:

• общую
сумму дохода за квартал;

• сумму
подоходного налога (13%);

• сумму,
подлежащую выдаче на руки.

2.
На плоскости заданы координаты трех
точек. Напишите сценарий, который
вычисляет площадь треугольника.

3.
Напишите сценарий, который для точки,
заданной координатами на плоскости,
определяет расстояние до начала
координат.

4.
Напишите сценарий, который обменивает
местами значения двух введенных
переменных.

5.
Напишите сценарий, который определяет
объем шара и площадь боковой поверхности,
если известен радиус.

6.
Задан радиус окружности. Определите
длину окружности и площадь соответствующего
круга.

7.
Задана окружность (координатами центра
и радиусом) и точка вне окружности.
Определите длину касательной из заданной
точки к окружности.

8.
Определите расстояние между двумя
точками на плоскости, заданными своими
координатами.

38

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]

  • #
  • #
  • #
  • #

    15.03.2016113.66 Кб8Я.doc

  • #
  • #
  • #
  • #
  • #
  • #
  • #

I have this two variables:

var a = 1,
    b = 2;

My question is how to swap them? Only this variables, not any objects.

asked Apr 24, 2013 at 20:35

Lukas's user avatar

1

Here’s a one-liner to swap the values of two variables.
Given variables a and b:

b = [a, a = b][0];

Demonstration below:

var a=1,
    b=2,
    output=document.getElementById('output');

output.innerHTML="<p>Original: "+a+", "+b+"</p>";

// swap values for variables "a" and "b"
b = [a, a = b][0];

output.innerHTML+="<p>Swapped: "+a+", "+b+"</p>";
<div id="output"></div>

answered Apr 24, 2013 at 20:39

showdev's user avatar

showdevshowdev

27.9k36 gold badges53 silver badges72 bronze badges

8

ES6 (Firefox and Chrome already support it (Destructuring Assignment
Array Matching)):

let a = 5, b = 6;
[a, b] = [b, a];
console.log(`${a} ${b}`);

Saksham's user avatar

Saksham

8,9056 gold badges44 silver badges71 bronze badges

answered Sep 18, 2014 at 10:58

Pedro Justo's user avatar

Pedro JustoPedro Justo

3,8691 gold badge16 silver badges21 bronze badges

7

You can do this:

var a = 1,
    b = 2,
    tmp;
tmp = a;
a = b;
b = tmp;

For readability and maintainability, this can’t be beat (at least in JavaScript). Anybody maintaining the code (including you six months from now) will know exactly what’s going on.

Since these are integers, you can also use any number of clever tricks1 to swap without using a third variable. For instance you can use the bitwise xor operator:

let a = 1, b = 2;
a = a ^ b;
b = a ^ b;
a = a ^ b;
    
console.log('a is now:', a);
console.log('b is now:', b);

This is called the XOR swap algorithm. Its theory of operation is described in this Wikipedia article.

1«The competent programmer is fully aware of the limited size of his own skull. He therefore approaches his task with full humility, and avoids clever tricks like the plague.» — Edsger W. Dijkstra

codejockie's user avatar

codejockie

8,4384 gold badges40 silver badges44 bronze badges

answered Apr 24, 2013 at 20:37

Ted Hopp's user avatar

Ted HoppTed Hopp

230k48 gold badges394 silver badges520 bronze badges

6

Don’t use the code below. It is not the recommended way to swap the values of two variables (simply use a temporary variable for that). It just shows a JavaScript trick.

This solution uses no temporary variables, no arrays, only one addition, and it’s fast.
In fact, it is sometimes faster than a temporary variable on several platforms.

It works for all numbers, never overflows, and handles edge-cases such as Infinity and NaN.

a = b + (b=a, 0)

It works in two steps:

  • (b=a, 0) sets b to the old value of a and yields 0
  • a = b + 0 sets a to the old value of b

Community's user avatar

answered Dec 11, 2013 at 23:04

Ruben Verborgh's user avatar

Ruben VerborghRuben Verborgh

3,5152 gold badges31 silver badges43 bronze badges

8

Since ES6, you can also swap variables more elegantly:

var a = 1,
    b = 2;

[a, b] = [b, a];

console.log('a:', a, 'b:', b); // a: 2 b: 1

answered Nov 4, 2015 at 10:24

Peter's user avatar

PeterPeter

6206 silver badges13 bronze badges

You can now finally do:

let a = 5;
let b = 10;

[a, b] = [b, a]; // ES6

console.log(a, b);

Dariuszrtk's user avatar

answered Apr 5, 2017 at 7:34

mehulmpt's user avatar

mehulmptmehulmpt

15.3k12 gold badges45 silver badges85 bronze badges

0

Here’s a one-liner, assuming a and b exist already and have values needing to be swapped:

var c=a, a=b, b=c;

As @Kay mentioned, this actually performs better than the array way (almost 2x as fast).

answered Nov 19, 2013 at 1:37

bobobobo's user avatar

bobobobobobobobo

63.6k60 gold badges254 silver badges354 bronze badges

1

You could use a temporary swap variable or XOR.

a = a ^ b
b = a ^ b
a = a ^ b

This is just a basic logical concept and works in every language that supports XOR operation.

edit: see the Comments. Forgot to tell that this works for sure only with integer. Assumed the integer variables from question’s thread

answered Apr 24, 2013 at 20:38

DmiN's user avatar

DmiNDmiN

7161 gold badge7 silver badges21 bronze badges

10

Use a third variable like this:

var a = 1,
    b = 2,
    c = a;

a = b; // must be first or a and b end up being both 1
b = c;

DEMO — Using a third variable


answered Apr 24, 2013 at 20:38

Nope's user avatar

NopeNope

22k7 gold badges46 silver badges72 bronze badges

As your question was precious «Only this variables, not any objects. «, the answer will be also precious:

var a = 1,
b = 2

a=a+b;
b=a-b;
a=a-b;

it’s a trick

And as Rodrigo Assis said, it «can be shorter «

 b=a+(a=b)-b;

Demo:
http://jsfiddle.net/abdennour/2jJQ2/

answered Apr 24, 2013 at 20:40

Abdennour TOUMI's user avatar

Abdennour TOUMIAbdennour TOUMI

82.9k37 gold badges237 silver badges246 bronze badges

9

ES6 Destructuring:

Using an array: [a, b] = [b, a]; // my favorite

Using an object: {a, b} = {a:b, b:a}; // not bad neither

answered Feb 13, 2018 at 7:34

Flavien Volken's user avatar

Flavien VolkenFlavien Volken

17.8k12 gold badges93 silver badges122 bronze badges

How could we miss these classic oneliners

var a = 1, b = 2
a = ({a:b, _:(b=a)}).a;

And

var a = 1, b = 2
a = (_=b,b=a,_);

The last one exposes global variable ‘_’ but that should not matter as typical javascript convention is to use it as ‘dont care’ variable.

Amal Murali's user avatar

Amal Murali

74.6k18 gold badges126 silver badges147 bronze badges

answered May 7, 2013 at 17:02

Teemu Ikonen's user avatar

Teemu IkonenTeemu Ikonen

11.8k4 gold badges22 silver badges35 bronze badges

5

I see kind of programming olympiad here. One more tricky one-line solution:

b = (function(){ a=b; return arguments[0]; })(a);

Fiddle: http://jsfiddle.net/cherniv/4q226/

answered Nov 21, 2013 at 7:49

Ivan Chernykh's user avatar

Ivan ChernykhIvan Chernykh

41.1k13 gold badges132 silver badges146 bronze badges

7

Single line swapping

a = a^b^(b^=(a^b));

Martijn's user avatar

Martijn

13k3 gold badges49 silver badges58 bronze badges

answered Jan 24, 2014 at 12:18

Saruselvi's user avatar

0

var a = 5;
var b = 10;

b = [a, a = b][0];
//or
b = [a, a = b];
b = b[0];

//or
b = [a, b];
a = b[1];
b = b[0];


alert("a=" + a + ',' + "b=" + b);

remove or comment the 2 //or’s and run with the one set of code

http://jsfiddle.net/USdv8/57/

answered Mar 26, 2015 at 5:17

Thilak Raj's user avatar

Thilak RajThilak Raj

8703 gold badges10 silver badges25 bronze badges

We are able to swap var like this :

var val1 =  117,
    val2 = 327;

val2 = val1-val2; 
console.log(val2);
val1 = val1-val2;
console.log(val1);
val2 = val1+val2;
console.log(val2);

answered Jan 13, 2015 at 10:35

Mohammed Javed's user avatar

Mohammed JavedMohammed Javed

8462 gold badges9 silver badges24 bronze badges

first way,

var a = 5, b = 9;

a = a - b;
b = a + b;
a = b - a;

console.log(a, b);

second way

var a = 19, b = 22;

[a, b] = [b, a];

console.log(a, b);

simple and clear answer.

answered Mar 14, 2022 at 4:49

rajkanani's user avatar

rajkananirajkanani

1433 silver badges5 bronze badges

Because I hear this method runs slower:

b = [a, a = b][0];

If you plan on storing your vars in an object (or array), this function should work:

function swapVars(obj, var1, var2){
    let temp = obj[var1];
    obj[var1] = obj[var2];
    obj[var2] = temp;
}

Usage:

let test = {a: 'test 1', b: 'test 2'};

console.log(test); //output: {a: 'test 1', b: 'test 2'}

swapVars(test, 'a', 'b');

console.log(test); //output: {a: 'test 2', b: 'test 1'}

answered Apr 16, 2020 at 17:55

SwiftNinjaPro's user avatar

We can use the IIFE to swap two value without extra parameter

var a = 5, b =8;
b = (function(a){ 
    return a 
}(a, a=b));

document.write("a: " + a+ "  b:  "+ b);

answered Apr 23, 2020 at 11:06

ganesh phirke's user avatar

ganesh phirkeganesh phirke

4411 gold badge3 silver badges11 bronze badges

Till ES5, to swap two numbers, you have to create a temp variable and then swap it.
But in ES6, its very easy to swap two numbers using array destructuring. See example.

let x,y;
[x,y]=[2,3];
console.log(x,y);      // return 2,3

[x,y]=[y,x];
console.log(x,y);      // return 3,2

Know more about JavaScript ES6 destructuring

answered Dec 31, 2019 at 12:04

Avinash Malhotra's user avatar

Although the same answer is given previously, but here is a png to describe it.

Simplest form possible:

enter image description here

answered Jan 1, 2022 at 2:51

MRPMOHIBURRAHMAN's user avatar

let a = 2, b = 4;
[b, a] = [a, b];

a more verbose approach would be

let a = 2, b = 4;
a = [a, b];
b = a[0];
a = a[1];

answered Feb 13, 2018 at 2:11

Enogwe Victor's user avatar

I have this two variables:

var a = 1,
    b = 2;

My question is how to swap them? Only this variables, not any objects.

asked Apr 24, 2013 at 20:35

Lukas's user avatar

1

Here’s a one-liner to swap the values of two variables.
Given variables a and b:

b = [a, a = b][0];

Demonstration below:

var a=1,
    b=2,
    output=document.getElementById('output');

output.innerHTML="<p>Original: "+a+", "+b+"</p>";

// swap values for variables "a" and "b"
b = [a, a = b][0];

output.innerHTML+="<p>Swapped: "+a+", "+b+"</p>";
<div id="output"></div>

answered Apr 24, 2013 at 20:39

showdev's user avatar

showdevshowdev

27.9k36 gold badges53 silver badges72 bronze badges

8

ES6 (Firefox and Chrome already support it (Destructuring Assignment
Array Matching)):

let a = 5, b = 6;
[a, b] = [b, a];
console.log(`${a} ${b}`);

Saksham's user avatar

Saksham

8,9056 gold badges44 silver badges71 bronze badges

answered Sep 18, 2014 at 10:58

Pedro Justo's user avatar

Pedro JustoPedro Justo

3,8691 gold badge16 silver badges21 bronze badges

7

You can do this:

var a = 1,
    b = 2,
    tmp;
tmp = a;
a = b;
b = tmp;

For readability and maintainability, this can’t be beat (at least in JavaScript). Anybody maintaining the code (including you six months from now) will know exactly what’s going on.

Since these are integers, you can also use any number of clever tricks1 to swap without using a third variable. For instance you can use the bitwise xor operator:

let a = 1, b = 2;
a = a ^ b;
b = a ^ b;
a = a ^ b;
    
console.log('a is now:', a);
console.log('b is now:', b);

This is called the XOR swap algorithm. Its theory of operation is described in this Wikipedia article.

1«The competent programmer is fully aware of the limited size of his own skull. He therefore approaches his task with full humility, and avoids clever tricks like the plague.» — Edsger W. Dijkstra

codejockie's user avatar

codejockie

8,4384 gold badges40 silver badges44 bronze badges

answered Apr 24, 2013 at 20:37

Ted Hopp's user avatar

Ted HoppTed Hopp

230k48 gold badges394 silver badges520 bronze badges

6

Don’t use the code below. It is not the recommended way to swap the values of two variables (simply use a temporary variable for that). It just shows a JavaScript trick.

This solution uses no temporary variables, no arrays, only one addition, and it’s fast.
In fact, it is sometimes faster than a temporary variable on several platforms.

It works for all numbers, never overflows, and handles edge-cases such as Infinity and NaN.

a = b + (b=a, 0)

It works in two steps:

  • (b=a, 0) sets b to the old value of a and yields 0
  • a = b + 0 sets a to the old value of b

Community's user avatar

answered Dec 11, 2013 at 23:04

Ruben Verborgh's user avatar

Ruben VerborghRuben Verborgh

3,5152 gold badges31 silver badges43 bronze badges

8

Since ES6, you can also swap variables more elegantly:

var a = 1,
    b = 2;

[a, b] = [b, a];

console.log('a:', a, 'b:', b); // a: 2 b: 1

answered Nov 4, 2015 at 10:24

Peter's user avatar

PeterPeter

6206 silver badges13 bronze badges

You can now finally do:

let a = 5;
let b = 10;

[a, b] = [b, a]; // ES6

console.log(a, b);

Dariuszrtk's user avatar

answered Apr 5, 2017 at 7:34

mehulmpt's user avatar

mehulmptmehulmpt

15.3k12 gold badges45 silver badges85 bronze badges

0

Here’s a one-liner, assuming a and b exist already and have values needing to be swapped:

var c=a, a=b, b=c;

As @Kay mentioned, this actually performs better than the array way (almost 2x as fast).

answered Nov 19, 2013 at 1:37

bobobobo's user avatar

bobobobobobobobo

63.6k60 gold badges254 silver badges354 bronze badges

1

You could use a temporary swap variable or XOR.

a = a ^ b
b = a ^ b
a = a ^ b

This is just a basic logical concept and works in every language that supports XOR operation.

edit: see the Comments. Forgot to tell that this works for sure only with integer. Assumed the integer variables from question’s thread

answered Apr 24, 2013 at 20:38

DmiN's user avatar

DmiNDmiN

7161 gold badge7 silver badges21 bronze badges

10

Use a third variable like this:

var a = 1,
    b = 2,
    c = a;

a = b; // must be first or a and b end up being both 1
b = c;

DEMO — Using a third variable


answered Apr 24, 2013 at 20:38

Nope's user avatar

NopeNope

22k7 gold badges46 silver badges72 bronze badges

As your question was precious «Only this variables, not any objects. «, the answer will be also precious:

var a = 1,
b = 2

a=a+b;
b=a-b;
a=a-b;

it’s a trick

And as Rodrigo Assis said, it «can be shorter «

 b=a+(a=b)-b;

Demo:
http://jsfiddle.net/abdennour/2jJQ2/

answered Apr 24, 2013 at 20:40

Abdennour TOUMI's user avatar

Abdennour TOUMIAbdennour TOUMI

82.9k37 gold badges237 silver badges246 bronze badges

9

ES6 Destructuring:

Using an array: [a, b] = [b, a]; // my favorite

Using an object: {a, b} = {a:b, b:a}; // not bad neither

answered Feb 13, 2018 at 7:34

Flavien Volken's user avatar

Flavien VolkenFlavien Volken

17.8k12 gold badges93 silver badges122 bronze badges

How could we miss these classic oneliners

var a = 1, b = 2
a = ({a:b, _:(b=a)}).a;

And

var a = 1, b = 2
a = (_=b,b=a,_);

The last one exposes global variable ‘_’ but that should not matter as typical javascript convention is to use it as ‘dont care’ variable.

Amal Murali's user avatar

Amal Murali

74.6k18 gold badges126 silver badges147 bronze badges

answered May 7, 2013 at 17:02

Teemu Ikonen's user avatar

Teemu IkonenTeemu Ikonen

11.8k4 gold badges22 silver badges35 bronze badges

5

I see kind of programming olympiad here. One more tricky one-line solution:

b = (function(){ a=b; return arguments[0]; })(a);

Fiddle: http://jsfiddle.net/cherniv/4q226/

answered Nov 21, 2013 at 7:49

Ivan Chernykh's user avatar

Ivan ChernykhIvan Chernykh

41.1k13 gold badges132 silver badges146 bronze badges

7

Single line swapping

a = a^b^(b^=(a^b));

Martijn's user avatar

Martijn

13k3 gold badges49 silver badges58 bronze badges

answered Jan 24, 2014 at 12:18

Saruselvi's user avatar

0

var a = 5;
var b = 10;

b = [a, a = b][0];
//or
b = [a, a = b];
b = b[0];

//or
b = [a, b];
a = b[1];
b = b[0];


alert("a=" + a + ',' + "b=" + b);

remove or comment the 2 //or’s and run with the one set of code

http://jsfiddle.net/USdv8/57/

answered Mar 26, 2015 at 5:17

Thilak Raj's user avatar

Thilak RajThilak Raj

8703 gold badges10 silver badges25 bronze badges

We are able to swap var like this :

var val1 =  117,
    val2 = 327;

val2 = val1-val2; 
console.log(val2);
val1 = val1-val2;
console.log(val1);
val2 = val1+val2;
console.log(val2);

answered Jan 13, 2015 at 10:35

Mohammed Javed's user avatar

Mohammed JavedMohammed Javed

8462 gold badges9 silver badges24 bronze badges

first way,

var a = 5, b = 9;

a = a - b;
b = a + b;
a = b - a;

console.log(a, b);

second way

var a = 19, b = 22;

[a, b] = [b, a];

console.log(a, b);

simple and clear answer.

answered Mar 14, 2022 at 4:49

rajkanani's user avatar

rajkananirajkanani

1433 silver badges5 bronze badges

Because I hear this method runs slower:

b = [a, a = b][0];

If you plan on storing your vars in an object (or array), this function should work:

function swapVars(obj, var1, var2){
    let temp = obj[var1];
    obj[var1] = obj[var2];
    obj[var2] = temp;
}

Usage:

let test = {a: 'test 1', b: 'test 2'};

console.log(test); //output: {a: 'test 1', b: 'test 2'}

swapVars(test, 'a', 'b');

console.log(test); //output: {a: 'test 2', b: 'test 1'}

answered Apr 16, 2020 at 17:55

SwiftNinjaPro's user avatar

We can use the IIFE to swap two value without extra parameter

var a = 5, b =8;
b = (function(a){ 
    return a 
}(a, a=b));

document.write("a: " + a+ "  b:  "+ b);

answered Apr 23, 2020 at 11:06

ganesh phirke's user avatar

ganesh phirkeganesh phirke

4411 gold badge3 silver badges11 bronze badges

Till ES5, to swap two numbers, you have to create a temp variable and then swap it.
But in ES6, its very easy to swap two numbers using array destructuring. See example.

let x,y;
[x,y]=[2,3];
console.log(x,y);      // return 2,3

[x,y]=[y,x];
console.log(x,y);      // return 3,2

Know more about JavaScript ES6 destructuring

answered Dec 31, 2019 at 12:04

Avinash Malhotra's user avatar

Although the same answer is given previously, but here is a png to describe it.

Simplest form possible:

enter image description here

answered Jan 1, 2022 at 2:51

MRPMOHIBURRAHMAN's user avatar

let a = 2, b = 4;
[b, a] = [a, b];

a more verbose approach would be

let a = 2, b = 4;
a = [a, b];
b = a[0];
a = a[1];

answered Feb 13, 2018 at 2:11

Enogwe Victor's user avatar

Понравилась статья? Поделить с друзьями:
  • Напишите сочинение на тему мать короткий праздник на земле
  • Напишите название времени года когда отмечают эти праздники new year christmas
  • Напишите литературный или режиссерский сценарий перешагни перескочи
  • Напишите возможный сценарий развития экономики при отсутствии наличных денег кратко
  • Направления на ноябрьские праздники

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии