简体   繁体   中英

Method toString is undefined JavaScript

I'm experimenting with key-value pair of JS objects.

<div id="parent" class="parent">
    <div id="child" class="child">
        <input type="text" class="text"/>
        <input id="submit" type="submit" onclick="doThis()"/>
    </div>
<div>

and corresponding JS code:

function doThis(){
    var span= document.createElement("span");
    var parent=document.getElementById("parent");
    var child=document.getElementById("child");
    var submit=document.getElementById("submit");
    child.insertBefore(span,submit);
    myKeys=[];
    for(var key in submit){
        myKeys.push("{"+key);
        myKeys.push(" "+submit.key + "}");
    }  
    span.innerHTML=myKeys;
}

It works correctly. But if we replace submit.key to submit.key.toString() it doesn't work. JSFIDDLE . I dont understand why the error's description is Uncaught TypeError: Cannot call method 'toString' of undefined. toString method defined for all JS object.

submit.key will be undefined since you meant submit[key]. Object accessors are required since you want to use the variable to lookup the property.

On checking what submit holds, I got

console.log(submit) 

returns

<input id="submit" type="submit" onclick="doThis()"/>

Whereas,

console.log(submit.key) //returns undefined

because submit does not hold key

Hence the error, toString() method cannot call of undefined

The problem you are facing is because of:

submit.key

you need to use:

submit[key]

Not only that, but calling toString() on this will fail if the key is null or undefined . So, better try-catch it and then review the log.

See your updated fiddle: http://jsfiddle.net/abhitalks/BYwz9/4/

Hope that helps.

Update : ( regarding the syntax of object key bracket notation )

From this reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime).

In order to check the difference it makes in your use-case, please change the fiddle to both notations and check the console log.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM