繁体   English   中英

如何解决array.length更改?

[英]How to fix the array.length changes?

此代码要求引入一个单词,将每个字母保存在数组中,然后向后返回。 我的问题是,当我引入单词“ mother”时,它返回“ undefinedrehtom”:那么,如果在循环中“ for”中指定数组长度应使得每个元素都被定义,那么为什么数组的第一个元素为“ undefined” ?

x = prompt("enter the text:");
var word = new Array();

for (i=0; i<x.length; i++) {
    word[i]= x.charAt(i);
}

for (j=word.length ; j>=0 ; j--) {
    document.write(word[j]);
}

数组的索引从0开始,因此您需要从array.length-1开始以获取最后的索引。

 x = prompt("enter the text:"); var word = new Array(); for (i=0; i<x.length; i++) { word[i]= x.charAt(i); } for (j=word.length-1 ; j>=0 ; j--) { document.write(word[j]); } 

有一种简单的方法可以反转字符串,

 var x = prompt("enter the text:"); var word = x.split("").reverse().join(""); document.write(word); 

首先,用“”分割,然后使用数组的反向方法,然后将它们加入。

length-1将起作用。

 x = prompt("enter the text:"); var word = new Array(); for (i=0; i<x.length; i++) { word[i]= x.charAt(i); } for (j=(word.length-1) ; j>=0 ; j--) { document.write(word[j]); } 

您在循环中出错。 word.length - 1 to 0而不是word.length to 0运行第二个循环

 x = prompt("enter the text:"); var word = new Array(); for (i=0; i<x.length; i++) { word[i]= x.charAt(i); } for (j=word.length - 1 ; j>=0 ; j--) { document.write(word[j]); } 

简单,

x = prompt("enter the text:");
var word = new Array();

for (i=0; i<x.length; i++) {
    word[i]= x.charAt(i);
}

for (j=word.length ; j>=0 ; j--) {  <<--- j value will be length of array in your case
                                          it will be 6
    document.write(word[j]);
}

由于数组以0开头,

word[0] = 'r' 
word[1] = 'e'
word[2] = 'h'
word[3] = 't'
word[4] = 'o'
word[5] = 'm'
word[6] =  ?????  JS doesnt know what it is so it will consider it as undefined.

解决方案:与其他建议一样,lenght-1将起作用,或者仅在for循环中使用j> 0也可以。

j = word.length -1之所以起作用,是因为您试图访问不存在的第五个索引,并且在循环开始时返回未定义

  x = prompt("enter the text:");
var word = new Array();

for (i=0; i<x.length; i++) {
    word[i]= x.charAt(i);
}

for (j=word.length -1 ; j>=0 ; j--) {
    document.write(word[j]);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM