由于对“未知”号码的测试实际上是一个服务器调用,因此您不能使用简单的循环来执行此操作。相反,您需要异步处理所有内容。
这是一个例子:
// Starting with guess, test that value and nearby integers up through
// guess+maxDelta and down through guess-maxDelta.
// Each number is tested by calling testMagicNumber(). This function
// can make an Ajax call or other asynchronous action, and then it
// should call the callback passed to it with true or false.
// When a match is found, call the callback function with that value.
// If no match is found call the callback function with false.
function findMagicNumber( guess, maxDelta, callback ) {
var delta = 0, sign = +1;
nextNumber();
function nextNumber() {
var value = guess + sign*delta;
//console.log( 'Testing', value );
testMagicNumber( value, function( match ) {
if( match ) {
callback( value );
}
else {
if( sign > 0)
++delta;
sign = -sign;
if( delta <= maxDelta )
nextNumber();
else
callback( false );
}
});
}
}
// Test version of a magic number matcher, using a hard coded value
function testMagicNumber( value, callback ) {
callback( value == magic );
}
// Untested example of a function to test a magic number
// with a server request. isMagic(result) is whatever test
// you need to make on the result to get a boolean value
// for the callback.
function testMagicNumberAjax( value, callback ) {
$.ajax({
url: 'test',
data: { value: value },
error: function() {
callback( false );
},
success: function( result ) {
callback( isMagic(result) );
}
});
}
for( var magic = 45; magic <= 55; ++magic ) {
console.log( 'Magic number is', magic );
findMagicNumber( 50, 3, function( result ) {
console.log( 'Matched', result );
});
}
这需要 50 的猜测和 3 的最大上下增量,并测试从 45 到 55 的幻数。
记录的结果是:
Magic number is 45
Matched false
Magic number is 46
Matched false
Magic number is 47
Matched 47
Magic number is 48
Matched 48
Magic number is 49
Matched 49
Magic number is 50
Matched 50
Magic number is 51
Matched 51
Magic number is 52
Matched 52
Magic number is 53
Matched 53
Magic number is 54
Matched false
Magic number is 55
Matched false
testMagicNumber() 函数是您进行 Ajax 调用以访问服务器的地方。当您从调用中得到响应时,testMagicNumber() 应使用true 或false 调用其callback 函数参数以指示号码是否匹配。 testMagicNumberAjax() 上面有一个示例(未经测试)Ajax 版本。
您可以将上面的代码粘贴到 Chrome 控制台中进行快速测试;更改magic 的值以尝试不同的数字。