这里阵列的长度是多少? [英] What is the length of the array here?
本文介绍了这里阵列的长度是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<p>hi</p>
<p>hello</p>
<p>hi</p>
<script>
var arr = document.getElementsByTagName("p");
for (var x = 0; x < arr.length; x++) {
arr[x].innerHTML = "Hi there";
}
</script>
</body>
</html>
我尝试过:
不是数组的长度(arr.length)等于1,因为只有1个元素p ?那么如果x只能小于数组的长度,这个条件如何在这段代码中工作?
What I have tried:
Isn't the length of the array (arr.length) equal to 1, since there's only 1 element "p"? So how does this condition work in this code if x can only be less than the array's length?
推荐答案
实际上有三个p
元素。试试
Actually there are threep
elements. Try
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<p>hi</p>
<p>hello</p>
<p>hi</p>
<script>
var arr = document.getElementsByTagName("p");
for (var x = 0; x < arr.length; x++) {
arr[x].innerHTML = "Hi there " + arr[x].textContent;
}
</script>
</body>
</html>
getElementsByTagName(p)获取全部< p>元素,有三个p元素,hi,hello和第二个hi,所以arr.length将是3,所以x将循环通过0,1,然后2,因为javascript数组被访问零基数所以0是第一个,第二个是第三个,所以它将设置所有三个元素的innerHTML。
getElementsByTagName("p") gets all <p> elements, and there are three p elements, "hi", "hello" and the second "hi", so arr.length will be 3, so x will loop through 0, 1, then 2, as javascript arrays are accessed on a zero-base so 0 is the first, 2 the third, so it will set the innerHTML of all three elements.
这篇关于这里阵列的长度是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文