Javascript 错误:无法将对象转换为原始值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6667291/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:43:36  来源:igfitidea点击:

Javascript Error: Cannot Convert Object to Primitive Value

javascriptobjectprimitive

提问by Eric

I'm receiving this error using the following javascript code:

我使用以下 javascript 代码收到此错误:

function tempTest(evt) {
    alert(evt.currentTarget.id);
    ct = document.getElementById(evt.currentTarget.id);
    rslt = document.getElementById('rslt');
    var props;
    for (var prop in ct) {
        if (ct.hasOwnProperty(prop)) {
            propVal = ct[prop];
            var propDat = prop + ' = ' + propVal;
            props += propDat + '<br/>';
        }
    }
    rslt.innerHTML = props;
}

This one has me puzzled. Any ideas?

这个让我很疑惑。有任何想法吗?

采纳答案by Itay Moav -Malimovka

Not all the properties of a HTML element are primitives. for example, parent, childs etc are also HTML elements. You can't just use them as strings or numbers.
You need to add there a condition and use that property accordingly.

并非 HTML 元素的所有属性都是基元。例如,父、子等也是 HTML 元素。您不能仅将它们用作字符串或数字。
您需要在那里添加一个条件并相应地使用该属性。

回答by Eliran Malka

(The OP:)

(OP:)

Just wanted to post the updated snippet for anyone who stumbles onto this post...

只是想为任何偶然发现这篇文章的人发布更新的片段...

function tempTest(evt) {
    alert(evt.currentTarget.id);
    ct = document.getElementById(evt.currentTarget.id);
    rslt = document.getElementById('rslt');
    var props;
    for (var prop in ct) {
        if (ct.hasOwnProperty(prop)) {
            var propVal = ct[prop];
            props += prop + ' (' + typeof(prop) + ')' + ' = ';
            if (typeof(ct[prop]) == 'string') {
                propVal += ct[prop];
            } else {
                if (propVal != null && propVal.toString) {
                    props += propVal.toString();
                } else {}
            }
            props += '<br/>';
        }
    }
    rslt.innerHTML = props;
}

回答by Glen Pierce

If the object in question is json, you can call JSON.stringify(thingThatIsJson)which will return a String. .toString()does not work on json.

如果有问题的对象是 json,您可以调用JSON.stringify(thingThatIsJson)which 将返回一个字符串。.toString()不适用于 json。

This is a message to those of you dealing with something like req.bodywhich will work in console.log()which is rather confusing since it may not otherwise behave like a String (like when you're trying to add it to another String).

这是给你们中那些处理类似的东西的人的消息,req.body这会console.log()很混乱,因为它可能不像字符串那样表现(比如当您尝试将它添加到另一个字符串时)。

回答by Ankit

The problem lies with the propValpart of your code. Since that may not be converted into a string.

问题在于propVal您的代码部分。因为那可能无法转换为字符串。