【问题标题】:Cannot read property length of undefined - Javascript无法读取未定义的属性长度 - Javascript
【发布时间】:2016-03-23 00:41:20
【问题描述】:

我是 javascript 新手,这段代码的主要目标是在文本框中输入一个问题,浏览器将检查问题是否在 switch 语句中并得到答案,而不是将其写在段落的 id="lable "。

  • 函数 randomArray(z)-line[8]- 返回一个随机数组值。

发生了什么:

在 id 为“lable”的段落上键入:“undefined”。
....... .....
HTML 代码:
<body>
<img src="Alexs_face.png">
    <p style="border:2px black solid; margin:100px 400px 50px 400px">Ask me     !</p>
<p id="lable"></p>
<input id="input" type="text" autocomplete="off">
<input id="send" type="button" onclick="dosome()"  value="Send">
<input id="delete" type="button" onclick="deleteVal()"  value="Delete"></body>

Javascript:

var greating , userName;



var firstHello = [[greating+userName+", How can I help you ?" ], ["Hi  "+userName+" how can i help ?"] ,[ greating+", how can i help ?"]];

dosome () ;

function randomArray (z) {  
var index = Math.floor(Math.random() * z.length);
return z[index];
};

 function getVal() {
write(randomArray (firstHello)); /* <------ trying to write a radom  value from the firstHello array
*/
 var ask = document.getElementById("input").value;
return ask ;}
var ask = getVal();
function write (x){
var lable = document.getElementById("lable").innerHTML = x;
return lable ;
};

//Capitalize the first letters func :
function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
//..............







//............................... you can ignore this function
function dosome () {

var ask = getVal();
var question = ask.split(" ");
var date = new Date().toTimeString().split(" ")[0]; ;
var userName ="Med" ;

 //5// give you different "greatings" according to ur time

 if (date >= "06:00:00" && date <="11:00:00"){
 greating = "Good morning ";
 var alertTime=""
}
else if (date >= "11:00:00" && date <= "15:00:00"){
greating = "Good afternoon ";
var alertTime=""
}
else if (date >= "15:00:00" && date <="22:00:00"){
greating = "Good evening ";
var alertTime=""
}
else {
greating = " You should have some sleep !";
 var alertTime = greating ; 
};
//5//end

//
if (question[0] === "what"){
switch ( question[1]){

case "time":
            switch (question[2]){
                case "is":
                          switch (question[3]){
                          case "it":
                          write("The time is :"+date+alertTime);
                          break;
                          default:
                          };
                break;
            default:    
            } ;
 break;
case "is":
          switch (question[2]){
              case "your" :
                           switch (question[3]){
                           case "name":
                           write("Alex !");
                           break;
                           case "father":
                           write("Medardo Erabti , he made me !");
                           break;
                           default:
                           };
              break;
              case "my":
              switch (question[3]){
                           case "name":
                           write("Alex !");
                           break;


                           default:
                           };
              break;
              default:

          };
break;

default: write("unknown");

};}
else if (question[0] === "my"){

switch (question[1]){
case "name":
           switch(question[2]){
               case "is":

                userName = capitalize(question[3]);;
                alert("Your name is saved, "+userName);
               break;

              default: 
           };
break;



default:
};
}
else if (question[0] === "should" || "could" || "may" || "can" )  {


switch (question[1]) {
case "i" :
      switch(question[2]){
      case "sleep":
      write("Sure ! you can sleep if you want to !!");
      break;
      default:
      }
break;

default:
};

}
if (question[0] === "who"){

switch (question[1]){

case "are":
write ("I'm Alex !");
break;
case "am":
write ("My leader !");
default:
 }

};

return userName,greating ;
};
function deleteVal () {

var x = document.getElementById("lable").innerHTML = "" ;
return x ;
};
  • 我尝试过的:

试图禁用函数 'randomArray(z)' 中的 'z' 参数并将其替换为数组的名称 "firstHello" ,其类型 "undefined 在以 "lable" 作为 id 的段落中。

【问题讨论】:

  • 附注。这是“问候”而不是“问候”
  • 对不起,意大利语是我的第一语言。 @zeropublix
  • @zeropublix:firstHello 变量是全局变量,因此可以在代码中的任何位置使用。
  • @Guffa:不。在前面写“var”意味着它不是全局的。如果您省略“var”,它将是全局的。如果我错了,请用来源纠正我
  • @zeropublix:如果代码在函数内部,使用var 只会使函数成为本地函数。当代码在全局范围内时,变量将是全局的。

标签: javascript arrays if-statement switch-statement


【解决方案1】:

dosome 函数中创建一个名为userName 的局部变量,与全局变量相同。局部变量会为函数内部的代码遮蔽全局变量,所以调用函数后全局变量仍然是未定义的。

randomArray函数中的代码注释:

  • 您使用的是Math.floor 而不是Math.random
  • 在创建整数随机数时不要使用Math.round,这会使第一个和最后一个数字出现的频率是其他数字的一半。请改用Math.floor
  • 您的循环超出了数组中最后一项的两项。
  • 您根本不需要循环来获取具有特定索引的项目。

以下代码仅显示修改后的 randomArray 函数和调用它的代码:

var greating = 'Hello', userName = 'sir';

var firstHello = [
  [ greating + " " + userName + ", How can I help you ?" ],
  [ "Hi " + userName + " how can i help ?" ],
  [ greating + ", how can i help ?" ]
];

function randomArray(z) {  
  var index = Math.floor(Math.random() * z.length);
  return z[index];
}

console.log(randomArray(firstHello));

【讨论】:

  • 您好,感谢您的回复,我编辑了循环,但是我应该如何处理这两个变量? @Guffa
  • @15YO-m:删除var userName ="Med" ; 中的var,以便它设置全局变量。
猜你喜欢
  • 1970-01-01
  • 2011-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-10
  • 2020-09-14
  • 2018-01-11
  • 2020-12-23
相关资源
最近更新 更多