Cannot read property "0" from undefined

honamiUeo
Tera Contributor

Script includes that handle arrays like the following will return an error at the for statement point
「error:Cannot read property "0" from undefined」
What is wrong?

 

var gr = new GlideRecord("tablename");
gr.addQuery("sys_id", "xxx");
gr.query();

var str;
var list = ["u_apple", "u_banana"];
        if (gr.next()) {
            for (var i = 0; i < list.length; i++) {
                if (gr.list[i]) {
                    str = "apple" + gr.list[i].getLabel();
                } else {
                    str = "banana" + gr.list[i].getLabel();
                }
            }
            gs.print(str);
}

 

1 ACCEPTED SOLUTION

Maddysunil
Kilo Sage

@honamiUeo 

The error you're encountering, "Cannot read property '0' from undefined", typically occurs when you're trying to access an element of an array that doesn't exist or is undefined. In your case, the issue is with how you're trying to access the fields of the GlideRecord object.

 

var gr = new GlideRecord("tablename");
gr.addQuery("sys_id", "xxx");
gr.query();

var str = "";
var list = ["u_apple", "u_banana"];

if (gr.next()) {
    for (var i = 0; i < list.length; i++) {
        if (gr.getValue(list[i])) { // Use getValue() method to check if field value exists
            str += "apple" + gr.getValue(list[i]) + "\n";
        } else {
            str += "banana" + gr.getValue(list[i]) + "\n";
        }
    }
    gs.print(str);
}

 

Please Mark Correct if this solves your query and also mark 👍Helpful if you find my response worthy based on the impact.

 

Thanks

View solution in original post

1 REPLY 1

Maddysunil
Kilo Sage

@honamiUeo 

The error you're encountering, "Cannot read property '0' from undefined", typically occurs when you're trying to access an element of an array that doesn't exist or is undefined. In your case, the issue is with how you're trying to access the fields of the GlideRecord object.

 

var gr = new GlideRecord("tablename");
gr.addQuery("sys_id", "xxx");
gr.query();

var str = "";
var list = ["u_apple", "u_banana"];

if (gr.next()) {
    for (var i = 0; i < list.length; i++) {
        if (gr.getValue(list[i])) { // Use getValue() method to check if field value exists
            str += "apple" + gr.getValue(list[i]) + "\n";
        } else {
            str += "banana" + gr.getValue(list[i]) + "\n";
        }
    }
    gs.print(str);
}

 

Please Mark Correct if this solves your query and also mark 👍Helpful if you find my response worthy based on the impact.

 

Thanks