Cannot successfully compare string values in a Near contract

Viewed 27

I am trying to compare string data taken off a Persistant Vector, with an if statement. However, the comparison is not working, it always evaluates to false in the if. The code is below with the comment, //trying to compare strings

export function removeStudent(rmstudidx: i32): string{

        let ablist = new Array<string>();
        let rmstudent: string = "";
        let abstudent: string = "";
        let abindx = new Array<i32>();
        let absentidx: i32;
        let x: i32 = 0;
        abstudent = studentlist[rmstudidx];
        if(studentlist.containsIndex(rmstudidx)){


                rmstudent = studentlist.swap_remove(rmstudidx);
                //return "Removed " + rmstudent;

        }
        while (x < absentlist.length){

                abstudent = studentlist[rmstudidx];
                if(rmstudent === abstudent){           //trying to compare strings

                        return "In the string test"
                        absentlist.swap_remove(x);
                        x++;
                }

        }
        return "Removed " + rmstudent;
} 
1 Answers

In your line, where you write

if(rmstudent === abstudent){

You are writing ===, which is not the same as === in JavaScript. AssemblyScript is strict, and using === will check if the objects are the same. If you want to do string comparison, you should use == instead.

Here's an example from the documentation of AssemblyScript

var a = "hello"
var b = a
var c = "h" + a.substring(1)

if (a === b) { /* true */ }
if (a === c) { /* false */ }
if (a == c) { /* true */ }
Related