gpt4 book ai didi

javascript - 以下 Javascript 数组场景中 parseInt() 和 Number.isInteger() 之间的功效差异?

转载 作者:行者123 更新时间:2023-11-30 06:15:50 24 4
gpt4 key购买 nike

我正在解决 freecodecamp.org 的 Javascript ES6 编码问题,其中一个问题要求我使用箭头函数表示法来:

  1. 取一组实数。
  2. 仅将正整数过滤到新数组中,并且
  3. 对这些正整数进行平方。

我已经成功地完成了这个问题,但是通过使用 Numbers.isInteger() 过滤原始数组来为第 2 步构建我的代码。 Freecodecamp.org 提供的答案使用 parseInt()。

我不明白为什么我们需要解析整数,如果它们已经是整数,也不明白为什么 parseInt() 不会抛出错误,因为它的参数要求一个字符串。

我的主要问题:两者是否同样可以接受?会不会给我带来更多麻烦?

我发现的唯一密切相关的 stackoverfow 是 here (这有点帮助)。下面是我的代码,后面是 freecodecamp.org 提供的答案代码。注意:我知道我的代码中有一些额外的步骤。我不是箭头符号的忠实粉丝,并且仍在改进我的代码组织!


我的代码::

const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];

const squareList = (arr) => {

"use strict";

// dictates what numbers are filter()'d out of original array

const checkElement = (value) => value > 0 && Number.isInteger(value) == true;

const integersOnly = arr.filter(checkElement); //filters ONLY positive integers into new array

提供的答案代码::

const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];

const squareList = (arr) => {

"use strict";

const squaredIntegers = arr.filter( (num) => num > 0 && num % parseInt(num) === 0 ).map( (num) => Math.pow(num, 2) );

最佳答案

I do not see why we would need to parse integers if they are already integers.

你不需要。这是对 parseInt 的滥用。他们应该使用 Math.floor 而不是他们的预期目的。

Why parseInt() does not throw an error since its parameter asks for a string?

因为它是一个旧的 API,而且非常宽松。它不会抛出错误,而只是将其参数强制转换为字符串,然后尝试对其进行解析。

My primary question: Are both equally acceptable?

不,parseInt 是绝对不能接受的。使用 isInteger,您找到了一个更好的解决方案。他们没有使用它的原因可能是 isInteger 是一个相对较新的函数,是 ES6 添加的。

关于javascript - 以下 Javascript 数组场景中 parseInt() 和 Number.isInteger() 之间的功效差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56212089/

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