javascript 在函数中使用 prompt() 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16382438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using a prompt() variable in a function
提问by Sebiddychef
In this code:
在这段代码中:
var ask = prompt("Enter contact's first name");
function Contact(firstName, surname, age) {
this.Name = firstName;
this.Surname = surname;
this.Age = age;
}
var contact = function (person) {
for (var prop in person) {
document.write(prop + ": " + person[prop] + "</br>");
}
};
var Alice = new Contact("Alice", "Example", 24);
var Bob = new Contact("Bob", "Bobby", 39);
contact(ask);
Why will it now work with the prompt box as the variable? It works fine when you just use a string in the contact function. Is it something to with because it is a variable not a string?
为什么它现在将提示框作为变量工作?当您只在联系函数中使用字符串时,它工作正常。是不是因为它是一个变量而不是一个字符串,所以它有什么关系?
回答by user1897690
Your for loop is iterating on the array of characters in the string. So it is actually working. Not sure what your goal is though.
您的 for 循环正在对字符串中的字符数组进行迭代。所以它实际上是有效的。不确定你的目标是什么。
The variables Alice and Bob are not used anywhere. That would make me think that you would like to be able to fetch some contacts data depending on the input. Modifying your contact function as follows (using eval) you will be able to match the input of the prompt with possible exising contacts variables:
变量 Alice 和 Bob 没有在任何地方使用。这会让我认为您希望能够根据输入获取一些联系人数据。如下修改您的联系函数(使用 eval),您将能够将提示的输入与可能的现有联系变量相匹配:
var contact = function (personName) {
var personObject = eval(personName)
for (var prop in personObject) {
document.write(prop + ": " + personObject[prop] + "</br>");
}
};
回答by Brad
You are calling your contact()
function with a string, and then trying to do a for...in
loop on it, which makes no sense. Sure, you can use for...in
with a string, but why would you want to? It just loops through each character.
您正在contact()
使用字符串调用您的函数,然后尝试对其进行for...in
循环,这是没有意义的。当然,您可以使用for...in
字符串,但为什么要使用呢?它只是遍历每个字符。
回答by Silinhower
i plugged this code into a compiler and it did not work because you are not using if statements to denote a function
我将此代码插入编译器,但它不起作用,因为您没有使用 if 语句来表示函数