You should iterate over the elements of the data array and print to the console the number of values in the array that are not NaN in Javasacript

huangapple go评论68阅读模式
英文:

You should iterate over the elements of the data array and print to the console the number of values in the array that are not NaN in Javasacript

问题

以下是翻译的代码部分:

let data = [11, null, NaN, 'Hello', 24]

let check = 0;

for (item in data) {
  if (isNaN(item) == false) {
    check +=1
  };
};

console.log(check);

请注意,这段代码中的注释和字符串部分没有进行翻译。

英文:

So here is my solution:

let data = [11, null, NaN, 'Hello', 24]

let check = 0;

for (item in data) {
  if (isNaN(item) == false) {
    check +=1
  };
};

console.log(check);

How ever the answer comes five, even though it is 2. I believe isNaN() function gives true or false, so why is it not working?

答案1

得分: 2

The in in item in data checks the properties of an object. In an array, the keys are numbers, you have five entries, so you get five times not isNan().

You want to iterate the array, so it should be let item of data

英文:

The in in item in data checks the properties of an object. In an array, the keys are numbers, you have five entries, so you get five times not isNan().

You want to iterate the array, so it should be let item of data

答案2

得分: 1

for...in 循环遍历对象的属性。要遍历数组的元素,请使用 for...ofArray#forEach

对于这个特定情况,Array#reduce 特别合适。

let data = [11, null, NaN, 'Hello', 24];
let res = data.reduce((a, b) => a + !isNaN(b), 0);
console.log(res);

希望这对你有帮助。

英文:

for...in loops over the properties of an object. To loop over an array's elements, use for...of or Array#forEach.

For this specific case, Array#reduce is particularly appropriate.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let data = [11, null, NaN, &#39;Hello&#39;, 24];
let res = data.reduce((a, b) =&gt; a + !isNaN(b), 0);
console.log(res);

<!-- end snippet -->

答案3

得分: 0

你的代码返回5,因为for...in循环遍历数组的键。而data数组的键是从04的数字,包括这两个数在内,总共有五个,都是数字。

有多种编写代码的方式。

使用for...in,使用item作为data中的索引(因为这就是它的作用):

const data = [11, null, NaN, 'Hello', 24]

let check = 0;
for (item in data) {
    if (isNaN(data[item]) == false) {
        check += 1;
    }
}

console.log(check);

使用for...ofitem是来自data的值,其余的代码都可以正常工作:

const data = [11, null, NaN, 'Hello', 24]

let check = 0;
for (item of data) {
    if (isNaN(item) == false) {
        check += 1;
    }
}

console.log(check);

使用Array.forEach()会将索引和值作为回调函数的参数。值是第一个参数,索引不是必需的(但作为第二个参数可用):

const data = [11, null, NaN, 'Hello', 24]

let check = 0;
data.forEach((item) => {
    if (isNaN(item) == false) {
        check ++;
    }
});

console.log(check);

Array.forEach()使用的回调函数更改了一个既不是参数也不是回调函数的本地变量。这种方式有些令人困惑,而且封装得不够好。虽然这种方式也可以,但可以使用Array.reduce()来更好地完成任务。Array.reduce()似乎更接近程序想要实现的目标,而不仅仅是一个更干净的编写两个之前提到的for循环的方法:

const data = [11, null, NaN, 'Hello', 24]

let check = data.reduce(
    (acc, item) => {
        if (isNaN(item) == false) {
            acc ++;
        }
        return acc;
    },
    0
);

console.log(check);

然而,Array.reduce()仍然不太合适。代码的目的是计算data数组中的数字。一个更自然的方式是不进行计数,而是使用Array.filter()将数字提取到一个新数组中。数组本身可以通过访问其length属性来告诉我们包含了多少项。无需使用if

const data = [11, null, NaN, 'Hello', 24]

const check = data.filter((item) => !isNaN(item)).length;

console.log(check);

其他注意事项:

  • 不要在代码块的右括号}后加分号。分号是语句分隔符,代码块可以在任何可以使用语句的地方使用。总的来说,下面的代码片段

    if (true) {
    };
    

    包含两个语句。一个是if (true),带有if分支上的空代码块,另一个是紧随代码块之后的空语句。

    在这里不会产生不良影响,但它可能是隐藏错误的根源,很难找到。

    分号仅在某些JavaScript语句之后才是必需的。对于其他情况,换行符和分号具有相同的作用。此外,JavaScript解释器能够自动插入一些丢失的分号

  • 不要使用==!=。它们进行松散比较(例如,2 == '2'),有时会产生令人惊讶的结果。始终使用严格相等运算符(===)严格不等运算符(!==)。它们首先检查两个操作数的类型,不会进行令人困惑的转换以检查值。

  • x += 1通常写作x++。请注意,在某些上下文中,x++++x具有不同的副作用。

  • 有时,使用逻辑非运算符(!)使代码更清晰。许多开发人员滥用它,生成"巧妙"但不清晰的代码,但在这里使用它比与false进行比较更好。对我来说,if (!isNaN(item))似乎更容易理解,而不是if (isNaN(item) === false)。它几乎可以阅读为:"如果item不是NaN"与"如果item不是NaN是false"。编写易于阅读和理解的代码。计算机不关心。

英文:

Your code returns 5 because for...in iterates over the array keys. And the array keys of data are the numbers between and including 0 and 4. Five in total, all of them are numbers.

There are multiple ways to write the code.

Using for...in, use item as an index in data (because this is what it is):
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const data = [11, null, NaN, 'Hello', 24]

let check = 0;
for (item in data) {
    if (isNaN(data[item]) == false) {
        check += 1;
    }
}

console.log(check);

<!-- end snippet -->

Using for...of, item is a value from data and the rest of your code works fine:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const data = [11, null, NaN, 'Hello', 24]

let check = 0;
for (item of data) {
    if (isNaN(item) == false) {
        check += 1;
    }
}

console.log(check);

<!-- end snippet -->

Using Array.forEach() you get both the index and the value as arguments of the callback function. The value is the first argument, the index is not needed (but it is available as the second argument):
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const data = [11, null, NaN, 'Hello', 24]

let check = 0;
data.forEach((item) =&gt; {
    if (isNaN(item) == false) {
        check ++;
    }
});

console.log(check);

<!-- end snippet -->

The callback function used by Array.forEach() changes a variable that is neither received as argument, nor a local variable of the callback function. The code is somewhat confusing this way and it is not properly encapsulated. While this is fine because there is not better option, here it can be done better using Array.reduce(). Array.reduce() seems to be closer to what the program wants to achieve than Array.forEach() (that is just a cleaner way to write the two for loops attended before).
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const data = [11, null, NaN, 'Hello', 24]

let check = data.reduce(
    (acc, item) =&gt; {
        if (isNaN(item) == false) {
            acc ++;
        }
        return acc;
    },
    0
);

console.log(check);

<!-- end snippet -->

However, Array.reduce() is still a wrong fit. The purpose of the code is to count the numbers from the data array. A more natural way is to not count them but to extract the numbers into a new array using Array.filter(). The array itself tells us how many items it contains by accessing its .length property. There is no need for ifs:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const data = [11, null, NaN, 'Hello', 24]

const check = data.filter((item) =&gt; !isNaN(item)).length;

console.log(check);

<!-- end snippet -->


Other remarks

Do not put semicolons (;) after the close brace } of a code block. The semicolon is a statement separator and a code block can be used wherever a statement can be used. All in all the following piece of code

if (true) {
};

... contains two statements. One is if (true) with an empty code block on the if branch, the other is an empty statement that follows the code block until the semicolon.

It does not have any undesired effect here but it can be the source of hidden bugs difficult to find.

The semicolon is required only after some JavaScript statements. For all the others, a new line works the same as a semicolon. More than that, the JavaScript interpreter is able to insert some missing semicolons automagically.

Attention! I do not say to never use semicolons. Use them where they must be used but be aware that a missing semicolon is either inserted by the interpreter or flagged as a syntax error (and the program does not start) while an extra semicolon in the wrong place can make your program behave in an unexpected way.


Do not use == and !=. They do loose comparisons (f.e. 2 == &#39;2&#39;) and sometimes they have surprising results. Always use the strict equality operator (===) and the strict inequality operator (!==). They first check the types of the two operands and do not do confusing conversions to check the values.


x += 1 is usually written x ++. Be aware that, in some contexts, x ++ is has different side effects than ++ x.

There is nothing wrong with += 1, just nobody uses it.


Sometimes, using the logical NOT operator (!) the code becomes more clear. It is abused by many developers that produce "clever" but unclear code but using it here is better than comparing against false.

To me, if (! isNaN(item)) seems easier to understand than if (isNaN(item) === false). It can almost be read: "if item is not NaN" vs. "if item is not NaN is false".<br>
It does not make any difference to the interpreter though. Write the code to be easy to read and understand. The computer does not care.

huangapple
  • 本文由 发表于 2023年2月14日 08:23:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75442401.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定