递归循环问题

时间:2017-01-09 07:18:47

标签: javascript for-loop

我正在尝试使用Recursive Loop在文本中搜索我的name

但它返回了一半的字母,有时还undefined



var text = 'huurrr hurrrh u rajat huhuhw dwhidwid sdijhsid \
    hurhrhr hrher rajat ekkdwihd ruidhwui rajat';

var myName = 'rajat';
var hits = [];

for (var i = 0; i < text.length; i++) {
  if (text[i] === 'r') {
    for (var j = i; j <= myName.length; j++) {
      hits.push(myName[j]);
    }
  }
}
console.log(hits);
&#13;
&#13;
&#13;

有人可以帮忙吗?

3 个答案:

答案 0 :(得分:0)

var text = 'huurrr hurrrh u rajat huhuhw dwhidwid sdijhsid \
    hurhrhr hrher rajat ekkdwihd ruidhwui rajat';

var myName = 'rajat';
var hits = [];

for (var i = 0; i < text.length; i++) {
  if (text[i] === myName[0] && text[i + 1] == myName[1]) {
    for (var j = 0; j <= myName.length; j++) {
      if(myName[j] == text[i + j])
        hits.push(myName[j]);
    }
  }
}
console.log(hits);

或者您可以使用正则表达式和String.prototype.match:

var text = 'huurrr hurrrh u rajat huhuhw dwhidwid sdijhsid \
    hurhrhr hrher rajat ekkdwihd ruidhwui rajat';
var myName = "rajat";
var regex= new RegExp(myName,"g");
var hits = text.match(regex);

console.log(hits)

答案 1 :(得分:0)

  

这可以在没有Recursive Loop的情况下实现,如下所示

var text = 'huurrr hurrrh u rajat huhuhw dwhidwid sdijhsid \ hurhrhr hrher rajat ekkdwihd ruidhwui rajat';


var regex = /rajat/gi, result, indices = [];
while ( (result = regex.exec(text)) ) {
    indices.push(result.index);
}
console.log(indices);// Array containing  index number where your string exists
console.log(indices.length); // Nmber of time occurence of string

答案 2 :(得分:0)

浏览代码

&#13;
&#13;
var text = 'huurrr hurrrh u rajat huhuhw dwhidwid sdijhsid \
    hurhrhr hrher rajat ekkdwihd ruidhwui rajat';

var myName = 'rajat';
var hits = [];

for (var i = 0; i < text.length; i++) {
  // You are assuming that if the word starts with "r" then the rest of the characters would "ajat", which is wrong.
  // Lets scan from the left of the text, it will go inside the if-condition as soon as it sees the `r` in the first `huurrr`.
  // Therefore when i = 3 (remember text[0] = h, text[1] = u, text[2] = u, text[3] = r), code will go inside the if-condition
  if (text[i] === 'r') { 
  	// Here you are assigning  `j=i` which means `j=3` and `myName.length = 5`, so it simplifies to
  	// for (var j = 3; j <= 5; j++) {
  	
    for (var j = i; j <= myName.length; j++) {
    	// When `j=3`, you trying to push a character from `myName` and not from `text`. 
    	// myName[3] = a , myName[4] = t , myName[5] = undefined (because index starts from 0 and there is nothing at index 5)  
      	hits.push(myName[j]);
    }
    // When above for loop finishes `hit` will have ["a", "t", undefined]
  }
  // Code will continue and execute for i = 4 and so on till it finishes
}
console.log(hits);
&#13;
&#13;
&#13;

如何修复

&#13;
&#13;
var text = 'huurrr hurrrh u rajat huhuhw dwhidwid sdijhsid \
    hurhrhr hrher rajat ekkdwihd ruidhwui rajat';

var myName = 'rajat';
var hits = [];

for (var i = 0; i < text.length; i++) {
	// We will use this if-condition as an entry condition
	if (text[i] === 'r') { 
		// No matter what the value of `i` is, we want to run the loop 5 times (5 is the length of myName) 
		// Lets initialize `j = 0` (because index of string starts from 0)
		// Also `j <= myName.length` should be `j < myName.length`, otherwise the loop would run 6 times
		for (var j = 0; j < myName.length; j++) {
			// We need additional checking to make sure we are looking for the string `rajat`
			// if `i=3`, (remember the word is "huurrr")
			// `text[3+0] = 'r'`, `text[3+1] = 'r'`, `text[3+2] = 'r'`, `text[3+3] = ' '`, `text[3+4] = 'h'`
			// That means code won't     
			if(text[i+j] === myName[j]){
				// For `j = 0`, hit will have the 1st character  (See below how to fix this flaw)
				hits.push(myName[j]);
			}else{ 
				// add an else condition so that this for loop execution stops even if a character does not match. 
				// That means, for `j=1`, it will break;
				break;
			}
		}
	}
}
console.log(hits);
&#13;
&#13;
&#13;

修复漏洞

&#13;
&#13;
var text = 'huurrr hurrrh u rajat huhuhw dwhidwid sdijhsid \
    hurhrhr hrher rajat ekkdwihd ruidhwui rajat';

var myName = 'rajat';
var hits = [];

for (var i = 0; i < text.length; i++) {
	if (text[i] === 'r') { 
		// To fix the flaw, I am going to use a boolean flag
		// The flag will have two states, true and false. 
		// I am going to keeep the default value of the flag as `true`
		var flag = true;

		// I am going to create a temp array to hold our values.
		// If the flag is true then only we will use it, 
		// because it means that tmp holds the characters ['r','a','j','a','t'].
		var tmp = [];

		for (var j = 0; j < myName.length; j++) {
			if(text[i+j] === myName[j]){
				tmp.push(myName[j]);
			}else{ 
				// If we come here, then it means there is a non matching character
				// so set flag as `false`
				flag = false;
				break;
			}
		}

		// check if flag is true, if yes then push values of tmp to hits
		if(flag === true){
			hits.push(...tmp); // The three dots is a way of spreading the elements, its called spread operator
		}
	}
}
console.log(hits);
&#13;
&#13;
&#13;

阅读The spread operator,下面的图片展示了如果我只使用hits.push(tmp);

将会发生什么

enter image description here

注意:您的问题有很多解决方案,这只是解决问题的一种方法