【问题标题】:How do i rewriting a function code javascript我如何重写功能代码javascript
【发布时间】:2021-04-28 21:34:36
【问题描述】:

一个函数,它包含each pair of numbers 与具有相同索引的参数的乘积。

var a = [3, 5, 7];
var b = [9, 10, 11];

a.map(function(x, index) { //here x = a[index] //how do i write this as function name(){}
  console.log(b[index] * x);
});

【问题讨论】:

    标签: javascript arrays function array.prototype.map


    【解决方案1】:

    这边

    var a = [3, 5, 7];
    var b = [9, 10, 11];
    
    function myFunction(x,index)
      {
      return (b[index] * x);
      }
    
    var c = a.map(myFunction);
    
    console.log( c )

    【讨论】:

      【解决方案2】:
      var a = [3, 5, 7];
      var b = [9, 10, 11];
      
      let c = [];
      
      function name(a, b) {
          a.map(function(x, index) {
               let result = b[index] * x;
               c.push(result);
           }
      }
      
      name(a, b);
      console.log(c) // this will show a new array with the results
      

      【讨论】:

      • 我如何以这种格式获得答案 [ , , ,] 到目前为止它以单独的值返回它
      • 我已经编辑了代码以显示一个名为 c 的新数组,它将以数组格式 [x, x, x] 显示结果
      • 天哪!!!你应该从.map而不是c.push(result)得到结果!!!
      【解决方案3】:

      您需要从map 回调中返回新值。

      var a = [3, 5, 7];
      var b = [9, 10, 11];
      
      const res = a.map((x,index)=>b[index] * x);
      console.log(res);

      【讨论】:

      • @niconi 您应该阅读这个答案,它应该可以工作!!!
      • @niconi 这应该是你的答案。
      【解决方案4】:

      .map() 的规格说:

      map() 方法creates a new array 填充了以下结果 在调用数组中的每个元素上调用提供的函数。

      var a = [3, 5, 7];
      var b = [9, 10, 11];
      
      function name(value_of_array_a, index_of_array_b) {
        return b[index_of_array_b] * value_of_array_a;
      } 
      
      var result = a.map(name);
      console.log(result);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-30
        • 1970-01-01
        • 2021-09-24
        • 2018-04-15
        • 1970-01-01
        • 2014-04-12
        • 1970-01-01
        • 2022-11-06
        相关资源
        最近更新 更多