【发布时间】:2016-10-29 22:34:15
【问题描述】:
我在 stackoverflow 上的第一篇文章!!!
我不确定为什么我的 function() 在 for 循环内的 if(statment) 中不起作用...
我了解解决方法。我可以在第一个匿名函数中添加一个 var answer 和 console.log,但我想了解为什么该函数不起作用......帮助!
我一直在学习绑定、调用、应用,并想创建这个示例来尝试它并偶然发现了这个问题。
var fruits = [];
var Fruit = function(name, color, quantity) {
this.name = name;
this.color = color;
this.quantity = quantity;
};
addFruit = function(name, color, quantity) {
fruits.push(new Fruit(name, color, quantity));
}
// filled fruits[] with objects.
addFruit("strawberry", "red", 20);
addFruit("watermelon", "green", 5);
addFruit("orange", "orange", 10);
// trying to console.log "an" instead of "a" because it preceeds "orange"
var greet = function() {
var vowels = "aeiou";
for (var i = 0; i < vowels.length; i++) {
if (this.name.charAt(0) === vowels.charAt(i)) {
// here is where this function does not work...
function() {
console.log("I am an " + this.name);
};
break;
}
else {
function() {console.log("I am a " + this.name)}
}
}
}
greet.call(fruits[2])
【问题讨论】:
-
忘记提及我为什么使用函数了! 2个原因。 1. 我在日志中发布了“我是橙子”和“我是橙子”。不是我想要的。 2.我不想在控制台中发布“我是草莓”5次,因为草莓中的“S”不是元音。
-
你在哪里调用过“不起作用”的匿名函数?
-
if (this.name.charAt(0) === vowels.charAt(i)) { // 这里是这个函数不起作用的地方... ******** ******* function() { *********** console.log("我是" + this.name); };
-
正确吗,您使用 === 而不是 == ?
-
请用您使用的语言标记问题。
标签: function if-statement for-loop call