[英]How to display string length in javascript
I am new to javascript, and today i was trying my first example as shown below in the code section. 我是Java语言的新手,今天我正在尝试我的第一个示例,如下代码部分所示。 I am using an editor called "Free Javascript Editor".
我正在使用一个名为“免费Javascript编辑器”的编辑器。 when I run the code, the browser starts and the text between the tags is displayed but the length of the string is never shown.
当我运行代码时,浏览器启动,并且显示标签之间的文本,但从未显示字符串的长度。
am I using it wrong?? 我使用错了吗? please let me know how to do it correctly
请让我知道如何正确做
lib compile 'io.reactivex.rxjava2:rxjava:2.0.1' compile 'io.reactivex.rxjava2:rxandroid:2.0.1' lib编译'io.reactivex.rxjava2:rxjava:2.0.1'编译'io.reactivex.rxjava2:rxandroid:2.0.1'
code : 代码 :
<html>
<head>
<title>Title of the home pahe</title>
</head>
<body>
<script>
var str = new string ("MyString");
str.length;
</script>
<h2>My First JavaScript</h2>
</body>
</html>
Use Onload event and put it inside js function. 使用Onload事件并将其放入js函数中。
<body onload="myFunction()">
<script>
function myFunction() {
var str = ("MyString");
var n = str.length;
document.getElementById("printlength").innerHTML = n;
}
</script>
<h2>My First JavaScript</h2>
<p id="printlength"></p>
</body>
Scripts are not rendered by the browser, only executed. 脚本不由浏览器呈现,仅执行。 You can, however, do something like this:
但是,您可以执行以下操作:
<html> <head> <title>Title of the home pahe</title> </head> <body> <h2>My First JavaScript</h2> <p id="theLength"></p> <script> // No need to invoke the string constructor here. var str = 'MyString'; // Find our placeholder element and set the textContent property. document.getElementById('theLength').textContent = str.length; </script> </body> </html>
It's good practice to put your script tags at the end of the body
element - that way all of the HTML should render before the scripts are executed. 好的做法是将脚本标记放在
body
元素的末尾-这样,所有HTML都应在执行脚本之前呈现。
Use document.createElement 使用document.createElement
var str = "MyString"; var p = document.createElement("p"); p.textContent = str.length; document.body.appendChild(p);
You should assign the length of your string to a variable. 您应该将字符串的长度分配给变量。 Then, you can show it.
然后,您可以显示它。
<span id="stringLength"></span> <script> var str = "MyString"; var length = str.length; document.getElementById('stringLength').textContent = 'Length: ' + length; // Show length in page console.log('Length: ' + length); // Show length in console alert('Length: ' + length); // Show length as alert </script>
Changed your code to this: 将您的代码更改为此:
<html>
<head>
<title>Title of the home pahe</title>
</head>
<body>
<script>
var str = "MyString";
console.log(str.length);
</script>
<h2>My First JavaScript</h2>
</body>
</html>
Then you must look in the developer console for the output, here is how: 然后,您必须在开发人员控制台中查找输出,方法如下:
It must be String, not string. 它必须是字符串,而不是字符串。 Code below works.
下面的代码有效。
var str = new String ("MyString");
str.length;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.