gpt4 book ai didi

javascript - 打印出迭代中的每个数组值,值是未定义的

转载 作者:行者123 更新时间:2023-11-28 14:15:10 25 4
gpt4 key购买 nike

我想打印出组合数组的内容。正如您所看到的,我在代码末尾调用了console.log,并且组合数组中的每个值都是未定义的。但是,如果我在其他地方(例如 if 语句)调用 console.log ,则值是正确的。请告诉我原因,谢谢!

$(function() {
var text = $('p').text().split('');
var letter = 0;
var composed = [];
$.each(text, function(index, value) {
if (/\w/.test(value)) { // if the character is alphanumeric
var prev = index - 1;
var next = index + 1;
if (/\w/.test(text[prev])) {
composed[letter] = composed[letter] + value;

if (!/\w/.test(text[next])) {
console.log('composed[' + letter + '] = ' + composed[letter]);
letter++;
}
} else {
composed[letter] = value;

if (!/\w/.test(text[next])) {
console.log('composed[' + letter + '] = ' + composed[letter]);
letter++;
}
}
} else {
composed[letter] = value;
console.log('composed[' + letter + '] = ' + composed[letter]);
letter++;
}
console.log('composed[' + letter + '] = ' + composed[letter]); // undefined
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Test both Chinese中文 ,alphbets and numbers.</p>

<小时/>

最佳答案

console.log('composed[' + letter + '] = ' + composed[letter - 1]);

这给出了正确的值

关于javascript - 打印出迭代中的每个数组值,值是未定义的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57816631/

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