David19801
David19801

Reputation: 11448

Why does this not work? javascript

I have this in Javascript:

var inx=[2,3,4,5];
var valarray=[];
for (i=0; i<inx.length; i++) {
    valarray[i]==inx[i];
}
for (i=0; i<inx.length; i++) {
    var posi=inx.indexOf(3);
    var valy=valarray[posi-1]+1;
    valarray[i]=valy;
}
alert(valarray);

valarray keeps returning nan,nan,nan,nan instead of numbers...

How can I fix this?

Upvotes: -1

Views: 140

Answers (6)

Martijn
Martijn

Reputation: 13632

The line valarray[i]==inx[i]; doesn’t do what you seem to expect it to.

In JS, = is the assignment operator, == the equality operator with type coercion, and === the strict equality operator.

A few examples:

var a;
alert(a = 2);       // 2

alert('2' == '2');  // true
alert(2 == 2);      // true
alert('2' == 2);    // true (because of type coercion, 2 == '2')

alert('2' === '2'); // true
alert(2 === 2.0);   // true
alert('2' === 2);   // false (strict equality: 2 !== '2')

Upvotes: 2

MiPnamic
MiPnamic

Reputation: 1267

    valarray[i]==inx[i];

must become

    valarray[i]=inx[i];

Upvotes: 0

Muhamad Bhaa Asfour
Muhamad Bhaa Asfour

Reputation: 1035

it is a javascript error only

you used :

valarray[i]==inx[i];

you should use :

valarray[i]=inx[i];

Upvotes: 0

NerdFury
NerdFury

Reputation: 19214

for (i=0; i<inx.length; i++) {
    valarray[i]==inx[i];
}

you are using a comparison operator (==), and not an assignment (=) operator here

Upvotes: 0

Kyle Macey
Kyle Macey

Reputation: 8154

 valarray[i]==inx[i];

That's a logical comparison, not an assignment.

 valarray[i]=inx[i];

Upvotes: 3

RYFN
RYFN

Reputation: 3069

You are comparing where you should be assigning, try this:

var inx=[2,3,4,5];
var valarray=[];
for (i=0; i<inx.length; i++) {
valarray[i]=inx[i]; //previously there was a == here
} 
for (i=0; i<inx.length; i++) {
var posi=inx.indexOf(3);
var valy=valarray[posi-1]+1;
valarray[i]=valy;
}
alert(valarray);

Upvotes: 0

Related Questions