所以代码学院说我正确地完成了这个但它没有产生任何结果。它应该精确定义“Alex”名称出现在var文本中的次数。有人可以告诉我我做错了吗?
注意:此当前代码的结果只是= []
提前谢谢,这是代码:
var text = "Alex, blah, Alex, blah, blah, blah, Alex, blah, Alex"
var myName = "Alex"
var hits = []
for (var i=0; i<text.length; i++){
if (text[i] === "A"){
for (var j = i; j < i + myName.length;j++){
hits.push(j);
}
}
}
if (hits.length = 0){
console.log("Your name wasn't found")
}
else{
console.log(hits);
}
答案 0 :(得分:0)
如果你被允许使用正则表达式,这很简单......
var text = "Alex, blah, Alex, blah, blah, blah, Alex, blah, Alex"
var myName = "Alex"
var hits = []
hits = text.match(new RegExp( "\\b"+myName+"\\b", "g"));
if (hits.length == 0){
console.log("Your name wasn't found")
}
else{
console.log(hits);
}
&#13;
答案 1 :(得分:0)
问题在这里:
hits.push(j); // you push index not symbol
应该是:
hits.push(text[j]);
我的解决方案:
var text = "af grwg rh thrthj jjy jtj Denys g er Denys";
var myName = "Denys";
var hits = [];
var k = 0;
for (var i = 0; i < text.length; i++){
if (text[i] === "D"){
for(var j = i; j < myName.length + i; j++){
hits.push(text[j]);
}
++k;
}
}
if (hits === []){
console.log("Your name wasn't found!");
}
else{
console.log("Your name was found " + k + " times!");
}
我也想问你:你知道https://discuss.codecademy.com吗?
我认为你可以更快地找到答案。但这是你的选择。
答案 2 :(得分:0)
顺便提一下,有一个简洁的数组方法叫做&#34; reduce&#34;接受一个数组并返回一个值。您可以使用String的拆分方法将文本转换为数组。
var text = "Alex, blah, Alex, blah, blah, blah, Alex, blah, Alex";
var textArray = text.split(', '); // split into an array
var myName = "Alex";
// reduce the array to a single value.
// Just increase a counter each time the name matches.
var total = textArray.reduce(function(prev, curr) {
if (curr === myName) ++prev;
return prev;
}, 0);
console.log(total);
// or if you want to get small.
// "Variables? Variables? We don't need no stinking' variables!"
console.log("Alex, blah, Alex, blah, blah, blah, Alex, blah, Alex".split(', ').reduce(function(prev, curr) {
return curr === "Alex" ? ++prev : prev;
}, 0));
&#13;