我一直在调试这几个小时无济于事。
以下代码检查一系列数字中的每个数字是否没有重复数字( 111应返回false ; 123应返回true ),并返回不包含重复数字的所有数字的数组。
该数组应该填充值,帮助器函数为数组中的每个值返回true ,但运行noRepeats()会导致无限循环或1的长阵列。 这是什么造成的?
// DO NOT RUN AS IS; POTENTIAL INFINITE LOOP var noRepeatDigits = function (n) { n = n.toString(); for ( i = 0 ; i < n.length ; i ++ ) { for ( j = i + 1 ; j < n.length ; j ++ ) { if ( n.charAt(i) === n.charAt(j) ) { return false; } } } return true; }; console.log( noRepeatDigits(113) ); // false console.log( noRepeatDigits(123) ); // true var noRepeats = function (n1, n2) { var arr = []; for ( i = n1 ; i <= n2 ; i ++ ) { if ( noRepeatDigits(i) ) { arr.push(i); } } return arr; }; console.log( noRepeats(1, 100) );I've been debugging this for hours to no avail.
The following code checks whether each number in a series of numbers has no repeating digits ( 111 should return false; 123 should return true) and return an array of all numbers in the series which contain no repeating digits.
The array should be populating with values which the helper function returns as true for each value in the array, but running noRepeats() causes an infinite loop or a long array of 1s. What is causing this?
// DO NOT RUN AS IS; POTENTIAL INFINITE LOOP var noRepeatDigits = function (n) { n = n.toString(); for ( i = 0 ; i < n.length ; i ++ ) { for ( j = i + 1 ; j < n.length ; j ++ ) { if ( n.charAt(i) === n.charAt(j) ) { return false; } } } return true; }; console.log( noRepeatDigits(113) ); // false console.log( noRepeatDigits(123) ); // true var noRepeats = function (n1, n2) { var arr = []; for ( i = n1 ; i <= n2 ; i ++ ) { if ( noRepeatDigits(i) ) { arr.push(i); } } return arr; }; console.log( noRepeats(1, 100) );最满意答案
你忘了var i ,所以迭代器是全局的,使用它的两个函数相互覆盖。 这最多会导致意外的行为,最坏的情况是无限循环。
但是,您可以简化您的noRepeatDigits功能:
noRepeatDigits = function(n) { return !n.toString().match(/(.).*?\1/); };这可以有效地完成原有功能,但将繁重的工作转移到内置的低级功能上,这些功能一般来说要快得多。
You forgot to var i, so the iterator is global and the two functions using it overwrite each other. This causes unexpected behaviour at best, an infinite loop at worst.
However you can simplify your noRepeatDigits function a lot:
noRepeatDigits = function(n) { return !n.toString().match(/(.).*?\1/); };This effectively does what your original function did, but offloads the heavy work to built-in, lower-level functions which generally speaking are significantly faster.
更多推荐
发布评论