我正在尝试从以下代码中将一个数组元素列表打印到另一个数组元素:
<html>
<body>
<p id="demo"></p>
<p id="demo1"></p>
<script>
var juice = [];
var fruits = [2, 5, 7, 10,15, 25,28,34,38,45,49,52,55,57,59];
for(int i =0;i < fruits.length;i++){
juice[i] = fruits[i];
}
document.getElementById("demo").innerHTML = juice.length;
document.getElementById("demo1").innerHTML = juice;
</script>
</body>
</html>
我没有从上面的代码中获得输出。
答案 0 :(得分:2)
基本上你有两个错误:
一个错误的变量声明
for(int i =0;i < oldArray.length;i++){
// ^^^
和第二个长度错误的变量
for (int i =0;i < oldArray.length;i++){
// ^^^^^^^^
var juice = [],
fruits = [2, 5, 7, 10, 15, 25, 28, 34, 38, 45, 49, 52, 55, 57, 59];
for (var i = 0; i < fruits.length; i++) {
juice[i] = fruits[i];
}
document.getElementById("demo").innerHTML = juice.length;
document.getElementById("demo1").innerHTML = juice;
&#13;
<p id="demo"></p>
<p id="demo1"></p>
&#13;
答案 1 :(得分:1)
使用slice()
复制数组:
<html>
<body>
<p id="demo"></p>
<p id="demo1"></p>
<script type="text/javascript">
var
juice = [],
fruits = [2, 5, 7, 10, 15, 25, 28, 34, 38, 45, 49, 52, 55, 57, 59];
juice = fruits.slice();
document.getElementById("demo").innerHTML = juice.length;
document.getElementById("demo1").innerHTML = juice;
</script>
</body>
</html>
slice()方法将数组的一部分的浅表副本返回到新的数组对象中。
答案 2 :(得分:1)
这对你有用。
<body>
<p id="demo"></p>
<p id="demo1"></p>
<script>
var juice = [];
var fruits = [2, 5, 7, 10,15, 25,28,34,38,45,49,52,55,57,59];
for(var i =0;i < fruits.length;i++){
juice[i] = fruits[i];
}
document.getElementById("demo").innerHTML = juice.length;
document.getElementById("demo1").innerHTML = juice;
</script>
</body>
</html>
答案 3 :(得分:0)
int i
- 它不是从JS代码复制的,并且未定义oldArray
,您在控制台中有错误。
尝试:
<html>
<body>
<p id="demo"></p>
<p id="demo1"></p>
<script>
var juice = [];
var fruits = [2, 5, 7, 10,15, 25,28,34,38,45,49,52,55,57,59];
for(var i =0;i < fruits.length;i++){
juice[i] = fruits[i];
}
document.getElementById("demo").innerHTML = juice.length;
document.getElementById("demo1").innerHTML = juice;
</script>
</body>
</html>
P.S。下次尝试不使用ctrl + c ctrl + v