【发布时间】:2017-01-01 17:17:57
【问题描述】:
我在入门课程之后尝试使用 apply 方法,发现了一些奇怪的行为 - 它将字符串作为字符数组读取,而不是读取字符串数组。
var john = {
name: 'John',
age: 26,
job: 'teacher',
listActivities: function(actList){
for (var i=0; i < actList.length; i++){
console.log("I enjoy "+actList[i]);
}
},
presentation: function(style, timeOfDay){
if(style=="formal"){
console.log('Good ' + timeOfDay + ' Ladies and Gentlemen! I\'m ' +this.name+', I\'m '+this.age+' and I\'m a '+this.job);
}
if(style=="friendly"){
console.log('Hi! How\'s it going? I\'m ' + this.name +', I\'m '+this.age+' and I\'m a '+this.job +'. Have a great '+timeOfDay);
}
}
};
var emily = {
name: 'Emily',
age: '35',
'job': 'designer'
};
john.presentation('formal','morning');
john.presentation.call(emily, 'friendly', 'afternoon');
john.listActivities(["golf", "Stroking animals", "Monty Python"]);
john.listActivities.apply(emily,["knitting", "cooking", "Monty Python"]);
John 列出活动的调用按预期工作。应用调用产生了
I like k
I like n
... 等到第一个单词的结尾。我知道字符串通常被实现为字符数组,但我不明白为什么它们在这里的访问方式如此不同。发生了什么事,我该如何解决?
【问题讨论】:
-
字符串被视为类似数组的对象,因为它具有
.length和数字索引。因此,您可以循环迭代它。apply方法将值数组传播到各个参数中,因此您在actList参数处引用"knitting"。 -
@squint:甚至不是这样。这只是 OP 误解了
apply的作用。 :-) -
@T.J.Crowder:这将是我评论中的最后一句话。 ;-)
-
是的,我所遵循的教程的措辞有点模棱两可,关于 apply 期望一个数组作为参数 - 这现在更清楚了!谢谢大家。
标签: javascript arrays string apply