为了账号安全,请及时绑定邮箱和手机立即绑定

下面两个代码有什么区别,(我运行了它们,但它们给出了不同的输出)

下面两个代码有什么区别,(我运行了它们,但它们给出了不同的输出)

哔哔one 2021-12-12 17:47:41
我正在用 JavaScript 做一个挑战,指令是将志愿者的数量除以社区的数量。我用.length数组的方法获取长度并执行了操作,但是让我烦恼的一件事是我尝试了两种方法,一种通过了,一种无法通过测试,代码如下这个通过了测试const function(volunteers, neighborhood){  let neighborhoodLent = neighborhood;  let volunteersLength = volunteers.length  let evaluate =  neighborhoodLent / volunteersLength;  return evaluate;}下面这个没有通过测试。const function(volunteers, neighborhood){  return volunteers.length / neighborhood.length}当给出一个像下面这样的数组时const volunteers = [  'Sally',  'Jake',  'Brian',  'Hamid'];const neighbourhoods = [  'Central Valley',  'Big Mountain',  'Little Bridge',  'Bricktown',  'Brownsville',  "Paul's Boutique",  'Clay Park',  'Fox Nest'];输出应该是2。我现在关心的是知道我使用的两种方法之间的区别以及为什么另一个通过了另一个失败了。请我将感谢您帮助澄清我
查看完整描述

3 回答

?
jeck猫

TA贡献1909条经验 获得超7个赞

你的第一个代码是如何通过的。按数字划分数组是 NaN。试试这个。


function calculate(volunteers, neighborhoods) {

    return volunteers.length / neighborhoods.length

}


查看完整回答
反对 回复 2021-12-12
?
幕布斯7119047

TA贡献1794条经验 获得超8个赞

看起来您使用了不正确的语法来声明函数。注意这function是 JavaScript 中的保留关键字。所以const function {...}不是有效的语法。您应该在function关键字后命名您的函数。试着这样写:


const volunteers = [

    'Sally',

    'Jake',

    'Brian',

    'Hamid'

];


const neighbourhoods = [

    'Central Valley',

    'Big Mountain',

    'Little Bridge',

    'Bricktown',

    'Brownsville',

    "Paul's Boutique",

    'Clay Park',

    'Fox Nest'

];


function calc (volunteers, neighborhood) {

    return neighborhood.length / volunteers.length;

}


const constCalc = (volunteers, neighborhood) =>{

    return neighborhood.length / volunteers.length;

}


console.log(`usual declaration`, calc(volunteers, neighbourhoods));

console.log(`arrow function:`, constCalc(volunteers, neighbourhoods));


查看完整回答
反对 回复 2021-12-12
?
呼唤远方

TA贡献1856条经验 获得超11个赞

结果应该是一样的


在方法中two而不是volunteers.length / neighbourhoods.length它应该是neighbourhoods.length / volunteers.length因为在诸如除法之类的数学运算中,因子的顺序会改变结果

固定代码:


const volunteers = ['Sally','Jake','Brian','Hamid']

const neighbourhoods = ['Central Valley','Big Mountain','Little Bridge','Bricktown','Brownsville',"Paul's Boutique",'Clay Park','Fox Nest']


const one = (volunteers, neighbourhoods) => {

  const neighbourhoodsLength = neighbourhoods.length

  const volunteersLength = volunteers.length

  const evaluate = neighbourhoodsLength / volunteersLength


  return evaluate

}


const two = (volunteers, neighbourhoods) => {

  return neighbourhoods.length / volunteers.length

}


console.log('one:', one(volunteers, neighbourhoods))

console.log('two:', two(volunteers, neighbourhoods))


查看完整回答
反对 回复 2021-12-12
  • 3 回答
  • 0 关注
  • 190 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信