猿问

类型错误:fns[(x * 2)] 不是函数

所以我有一个作业问题需要解决。要求只是修复代码,以便控制台显示 true


 var x = 2,

 fns = [];


(function () {

  var x = 5;


  for (var i = 0; i < x; i++) {

  //  write here 

  }

})();


// DO NOT MODIFY BELOW CODE

console.log(x * 2===fns[x * 2]());

// console must show true

控制台输出是


未捕获的类型错误:fns[(x * 2)] 不是函数


我尝试重写函数作为数组中的元素之一,但控制台仍然显示错误。我重写了fns[x * 2]()to fns[x * 2],控制台显示 return false (这很好,因为至少它不会抛出错误),但无法根据要求修改它


蝴蝶刀刀
浏览 137回答 2
2回答

Qyouu

数组的每个元素都需要是一个返回其在数组中当前索引的函数:var x = 2,&nbsp; fns = [];(function() {&nbsp; var x = 5;&nbsp; for (let i = 0; i < x; i++) {&nbsp; &nbsp; fns[i] = () => i;&nbsp; }})();// DO NOT MODIFY BELOW CODEconsole.log(x * 2 === fns[x * 2]());// console must show true确保用 ,&nbsp;letnot声明索引变量var(var&nbsp;有问题)。或者,更实用的是:const fns = Array.from(&nbsp; { length: 5 },&nbsp; (_, i) => () => i);let x = 2;// DO NOT MODIFY BELOW CODEconsole.log(x * 2 === fns[x * 2]());// console must show true

鸿蒙传说

您需要一个带有 IIFE 的闭包来获取该值。var x = 2,&nbsp; &nbsp; fns = [];(function() {&nbsp; &nbsp; var x = 5;&nbsp; &nbsp; for (var i = 0; i < x; i++) {&nbsp; &nbsp; &nbsp; &nbsp; fns[i] = function (v) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return function () { return v; };&nbsp; &nbsp; &nbsp; &nbsp; }(i);&nbsp; &nbsp; }})();// DO NOT MODIFY BELOW CODEconsole.log(x * 2 === fns[x * 2]());// console must show true
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答