gpt4 book ai didi

javascript - 带有 && 和 .length 的 if 语句

转载 作者:行者123 更新时间:2023-11-28 19:17:42 25 4
gpt4 key购买 nike

我想知道当我将两个 if 条件组合在一起时,为什么控制台显示“无法读取未定义的属性‘长度’”?

//After two if's combined by &&:
for(n= 0, len=i.length; n<len; n++) {
if(typeof n[i] !== 'string' && n[i].length > longest.length)
longest = n[i];
}


// Before I combine two if's:
for(n= 0, len=i.length; n<len; n++) {
if(typeof n[i] !== 'string') continue;
if(n[i].length > longest.length) longest = n[i];
}

最佳答案

其他人指出了为什么它不起作用,但没有找到解决方案,因为你的变量名称不是很清楚。也许就是这样:

var i = ['a', 12, 'hello', 'hi', {}, 1.1, 'hey'],
longest = '';

for(n= 0, len=i.length; n<len; n++) {
if(typeof i[n] === 'string' && i[n].length > longest.length) longest = i[n];
}

alert('Longest string found: ' + longest);

关于javascript - 带有 && 和 .length 的 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29499102/

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