gpt4 book ai didi

javascript - For 循环返回奇怪的长度

转载 作者:行者123 更新时间:2023-11-28 11:30:51 26 4
gpt4 key购买 nike

我有这个 JavaScript 代码:

var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
key = '',
c;

for (i = 0; i < 32; i++) {
c = Math.floor(Math.random() * chars.length + 1);
key += chars.charAt(c)
}

console.log('return key length that needs to be 32...' + key.length);

我需要始终返回 32 key 长度..但我得到随机:

return key length that needs to be 32...31
return key length that needs to be 32...29
return key length that needs to be 32...32
return key length that needs to be 32...31
return key length that needs to be 32...30
return key length that needs to be 32...32
return key length that needs to be 32...31

我知道错误在于:i<32;,但当我添加 i=32; 时,javascript 卡住了,我尝试了 i<=32 但结果相同...所以我知道这是基本问题,但我不知道总是返回 32 个 key 长度?

最佳答案

问题出在这一行中的+ 1:

c = Math.floor(Math.random() * chars.length + 1);

有效索引从 0chars.length-1。上面的赋值从 1chars.length 中选择一个随机数。因此它会忽略字符串中的第一个字符,有时会尝试访问字符串之外的内容。在后一种情况下,它 chars.charAt(c) 返回 undefined,并且追加不会增加结果的长度。

var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
key = '',
c;

for (i = 0; i < 32; i++) {
c = Math.floor(Math.random() * chars.length);
key += chars.charAt(c)
}

console.log('return key length that needs to be 32...' + key.length);

关于javascript - For 循环返回奇怪的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49114114/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com