简体   繁体   English

为什么无法在Array中检测到更大的JavaScript字符串?

[英]Why can't detect the bigger JavaScript String in Array?

This is a part from my code.I'm doing a javascript exercise. 这是我的代码的一部分。我正在做一个javascript练习。

switch(size) {
   case "big":
        var nameSize = "";
        if(fNames[i].length > nameSize.length) {
            nameSize = fNames[i];
        }
        console.log("Your Female Big: " + nameSize);
   break;

The user chooses the name with "big" size (the biggger string in array) through a prompt() . 用户通过prompt()选择“big”大小的名称(数组中的biggger字符串prompt() I trying to verify if fNames[i] is the bigger string in my array fNames to return for the user, but isnt working, it is return all strings. 我试图验证fNames[i]是否是我的数组fNames中为用户返回的更大的字符串,但是不工作, 它返回所有字符串。 . What am I doing wrong? 我究竟做错了什么?

----> JSfiddle ----> JSfiddle

Update 更新

This code works: 此代码有效:

var array = [3, 6, 2, 56, 32, 5, 89, 32];
var largest = 0;
for(i = 0; i < array.length; i++) {
    if(array[i] > largest) {
        largest = array[i];
    }
}
console.log(largest);

(from codecademy) (来自codecademy)

It is the same logic, i think. 我认为这是相同的逻辑。 Why my code does not work, then? 为什么我的代码不起作用呢?

I think you should add .length : 我想你应该添加.length

nameSize = fNames[i].length;

If this is happening inside a loop you should check the length of the biggest compared to the var in the loop: 如果在循环内发生这种情况,你应该检查最大的长度与循环中的var相比:

var name = '';
if(fNames[i].length > name.length) {
    name = fNames[i];
}

Notice that in the if you use .length on both the variables. 请注意, if在两个变量上都使用.length

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM