我试图了解这段代码的工作原理,但我不是Java专家。
基本上,我需要使用nodejs打开它并键入正确的密码,但是我对“ nums [x]”的工作方式感到困惑。
const readline = require('readline')
const reader = readline.createInterface({
input: process.stdin,
output: process.stdout
})
const chars = [
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
]
const transformStr = function (str, a, b) {
str = str.split('')
const first = a % str.length
const last = b % str.length
const temp = str[first]
str[first] = str[last]
str[last] = temp
return str.join('');
}
const validate = function (str) {
if (str.length != 8)
return false
str = transformStr(str, 17, 10)
const nums = str.split('').map(c => chars.indexOf(c))
if (nums[1] != Math.pow(nums[6], 2) - 1)
return false
if (4 * nums[1] != nums[7])
return false
if (nums[5] != 46)
return false
if (nums[4] != nums[5] + nums[6])
return false
if (nums[3] != nums[4] + 2)
return false
if (nums[2] - nums[3] != nums[1] - nums[6])
return false
if (nums[0] != nums[2] + 4)
return false
const result = nums.reduce((n1, n2) => n1 + n2)
if (result != 305)
return false
return true
}
const question = "Type the password: "
reader.question(question, function(password) {
reader.close();
const valid = validate(password)
if (valid)
console.log("Congrats, you got it!")
else
console.log("Wrong password, try again.")
})
我认为我了解“ transformStr”函数,但是“ validate”函数中的nums = str.split('').map(c => chars.indexOf(c))
却使我很沮丧。
答案 0 :(得分:-1)
say str是'012345678A',str.split('').map(c => chars.indexOf(c))
将在新数组中返回str
数组中每个字符(chars
)的索引,因此返回结果将是{{1 }}其余的只是检查返回数组的索引是否相等,不相等等。这是Array.prototype.map和Array.prototype.reduce的文档
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce希望对您有帮助