【问题标题】:Convert JavaScript Array [a, b, c, d, e] into [a+b, b+c, c+d, d+e] dynamically将 JavaScript Array [a, b, c, d, e] 动态转换为 [a+b, b+c, c+d, d+e]
【发布时间】:2021-01-18 11:14:32
【问题描述】:

我有一个数组[a, b, c, d, e, .....]

如何像[a+b, b+c, c+d, d+e, ....]这样转换

reducer 可能是最好的方法,但如何在计算后存储临时内存。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

请检查此代码

function randomIntegerArray(length) {
  const random = Math.floor(
    Math.pow(10, length - 1) +
      Math.random() * (Math.pow(10, length) - Math.pow(10, length - 1) - 1),
  );
  return String(random).split('');
}
 const makeQuestions = (del, len) =>
    new Array(len)
      .fill(randomIntegerArray(del))
      .map((row, index) => {
      
      // row [a, b, c, d, e]
      // ans [a+b, b+c, c+d, d+e]
      let ans = [];
      
        return {
          question: row,
          answer: ans,
        };
      } );
      
      console.log(makeQuestions(5, 2));

【问题讨论】:

  • id: index + 1, question: row, desc: '', ref: '', options: '', answer: ans, 与您提出的问题有什么关系?你能创建一个minimal reproducible example 吗?
  • 上次迭代中的第二个和数是多少?

标签: javascript arrays algorithm


【解决方案1】:

您的代码中存在一些问题:

  • randomIntegerArray 函数只能处理最大约 17 的长度,...对于更大的值,它将继续产生超过索引 17 的零。这是因为浮点具有精度限制。

  • randomIntegerArray 函数并没有像它的名字所说的那样做:它产生一个字符串数组,而不是整数

  • randomIntegerArray 函数永远不会在索引 0 处产生零。

  • randomIntegerArray 函数不能产生大于 9 的数字。

  • 您的代码仅生成 一个 这样的随机数组,然后使用 fill 将该单个数组分配给问题数组中的多个插槽。尽管您的问题并不清楚,但您似乎更有可能希望生成与“问题”一样多的随机数组。

您可以通过以下方式完成这项工作,同时解决上述问题:

const randomIntegerArray = (length, max=9) =>
    Array.from({length}, () => Math.floor(Math.random() * (max+1)));

const makeQuestions = (del, length) =>
    Array.from({length}, () => randomIntegerArray(del))
         .map((question, index) => ({
            question,
            anser: question.slice(0, -1)
                           .map((item, index) => item + question[index+1])
          }));
      
console.log(makeQuestions(5, 2));

【讨论】:

    【解决方案2】:

    您拥有原始数组row,并且您知道两个数组之间的预期长度和预期关系,因此您可以通过以下方式实现:

    function randomIntegerArray(length) {
      const random = Math.floor(
        Math.pow(10, length - 1) +
          Math.random() * (Math.pow(10, length) - Math.pow(10, length - 1) - 1),
      );
      return String(random).split('');
    }
     const makeQuestions = (del, len) =>
        new Array(len)
          .fill(randomIntegerArray(del))
          .map((row, index) => {
          
          // row [a, b, c, d, e]
          // ans [a+b, b+c, c+d, d+e]
          let ans = row.slice(0,-1).map((item, index) => Number(item) + Number(row[index+1]));
          
            return {
              id: index + 1,
              question: row,
              desc: '',
              ref: '',
              options: '',
              answer: ans,
            };
          } );
          
          console.log(makeQuestions(5, 2));

    【讨论】:

    • 很好的解决方案 >>> row[index+1]
    【解决方案3】:

    您可以为此使用reduce

    const a = 1, b = 2, c = 3, d = 4, e = 5;
    
    const result = [a, b, c, d, e].reduce((acc, el, i, sourceArr) => {
      if (i < sourceArr.length - 1) {
        acc.push(el + sourceArr[i + 1]);
      }
      return acc;
    }, []);
    
    console.log(result);

    它使用.reduce()回调的第三个(索引)和第四个(源数组)参数过滤掉最后一个元素,并获取数组的下一个元素进行计算。

    在你的例子中:

    function randomIntegerArray(length) {
      const random = Math.floor(
        Math.pow(10, length - 1) +
        Math.random() * (Math.pow(10, length) - Math.pow(10, length - 1) - 1),
      );
      return String(random).split('');
    }
    const makeQuestions = (del, len) =>
      new Array(len)
      .fill(randomIntegerArray(del))
      .map((row, index) => {
    
        // row [a, b, c, d, e]
        // ans [a+b, b+c, c+d, d+e]
        let ans = row.reduce((acc, el, i, sourceArr) => {
          if (i < sourceArr.length - 1) {
            acc.push(el + sourceArr[i + 1]);
          }
          return acc;
        }, []);
    
        return {
          question: row,
          answer: ans,
        };
      });
    
    console.log(makeQuestions(5, 2));

    请注意,因为row 是一个字符串数组,所以它将连接字符串而不是计算加法。如果要进行加法运算,可以将arr 转换为数字数组,或者将el + sourceArr[i + 1] 更改为+el + +sourceArr[i + 1]

    【讨论】:

      【解决方案4】:

      您可以将Array#mapArray#slice 结合使用,如下所示:

      const a = 1, b = 2, c = 3, d = 4, e = 5;
      const array = [a, b, c, d, e];
      const result = array.map((v, index) => v + array[index+1]);
      
      console.log(result.slice(0, array.length - 1));

      【讨论】:

        猜你喜欢
        • 2012-01-27
        • 1970-01-01
        • 1970-01-01
        • 2018-09-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-23
        • 1970-01-01
        相关资源
        最近更新 更多