Javascript 为什么 string.length 返回未定义?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4979232/
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 15:03:38  来源:igfitidea点击:

why string.length return undefined?

javascript

提问by pierrotlefou

In the popup window, selText does have the value "great," but the length is always undefined. Something related with the encoding of the string?

在弹出窗口中,selText 确实具有值“great”,但长度始终为undefined。与字符串编码有关的东西?

var selText = document.getSelection(); //suppose "great" is selected
alert( "selected ->" + selText + " len is " + selText.length);

回答by user113716

Because you're getting a DOM selection object instead of a String. To get the text, call toString().

因为你得到的是一个 DOM 选择对象而不是一个字符串。要获取文本,请调用toString()

var selText = document.getSelection().toString();

The reason the string successfully shows up in the alert, is that the concatenation causes an implicit toString()to occur.

字符串成功显示在警报中的原因是连接导致隐式toString()发生。

回答by John K

The MDN documentationstates.

MDN文档的状态。

In the above example, selObj is automatically "converted" when passed to window.alert. However, to use a JavaScript String property or method such as length or substr, you must manually call the toString method.
-- https://developer.mozilla.org/en/window.getSelection

在上面的例子中,selObj 在传递给 window.alert 时会自动“转换”。但是,要使用 JavaScript 字符串属性或方法(例如 length 或 substr),您必须手动调用 toString 方法。
-- https://developer.mozilla.org/en/window.getSelection

It's suggesting you call document.getSelection().ToString().length;

建议你打电话 document.getSelection().ToString().length;

回答by The Mask

Deprecated method document.getSelection() Try use window.getSelection().

不推荐使用的方法 document.getSelection() 尝试使用 window.getSelection()。

var selText = window.getSelection().toString();
        if(selText)
        {
            alert( "selected ->" + selText + " len is " + (selText.length - 1));
        }