[英]i keep getting this error “Uncaught TypeError: name.push is not a function at <anonymous>:10:7”
var name = []; var input = prompt("what u want?"); while (input !== "quit"){ if (input === "list"){ console.log(name); } else if(input === "new"){ var hold = prompt("Enter"); name.push(hold); } input = prompt("What u want?"); } console.log("u quit");
You can't change the type of name
as it is already defined globally . 您无法更改已全局定义 的
name
类型 。 Use a different variable - name1
. 使用其他变量 -
name1
。
var name1 = []; var input = prompt("what u want?"); while (input !== "quit") { if (input === "list") { console.log(name1); } else if (input === "new") { var hold = prompt("Enter"); name1.push(hold); } input = prompt("What u want?"); } console.log("u quit");
Issue in your code is that, any variable that is defined outside any function is added in global scope( window
). 代码中的问题是,在任何函数之外定义的任何变量都会添加到全局范围(
window
)中。 Now window
already has a property called name and you cannot override it. 现在
window
已经有一个名为name的属性,你不能覆盖它。 Hence it throws error. 因此它会抛出错误。
Solution: 解:
(function() { var name = []; var input = prompt("what u want?"); while (input !== "quit") { if (input === "list") { console.log(name); } else if (input === "new") { var hold = prompt("Enter"); name.push(hold); } input = prompt("What u want?"); } console.log("u quit", name); })()
Note: its a bad practice to bleed to global scope. 注意:向全局范围流血是一种不好的做法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.