【问题标题】:multiply each element in array by 2 using 'for' loop使用'for'循环将数组中的每个元素乘以2
【发布时间】:2019-02-10 16:48:47
【问题描述】:

我正在尝试将数组中的每个元素加倍

let arr =  ['onions', 'tomatoes', 'etc'...';

使用 for 循环并不断收到 NaN 错误...我仍在学习,因此不胜感激。

我试过for循环、.map()等方法,就是看不出明显的问题……

let newIngr = tortSoup.filter(function(value, index, arr) {
  if (value !== 'onion' && value !== 'red pepper') {
    return value;
    console.log(newIngr);
  });       
}

let myReci = [];

for(var i = 0; i < newIngr.length; i++) {
  myReci[i] = newIngr[i] * 2;
}

console.log(myReci);

预期:每个数组元素乘以 2 并返回:

['onions', tomatoes', 'garlic', 'fontina']

会变成:

['onions', 'onions', 'tomoatoes', 'tomatoes', garlic, 'garlic', 'fontina', 'fontina']

【问题讨论】:

  • string * 2 不会向您返回 2 个字符串。它将返回 NaN
  • [Hint] : 考虑在循环中使用 Array#push() 两次

标签: javascript arrays loops for-loop


【解决方案1】:

这是一种使用Array.reduce() 和扩展运算符的方法:

const array = ['onions', 'tomatoes', 'garlic', 'fontina'];

const result = array.reduce((acc, x) => ([...acc, x, x]), []);

console.log(result)

Array.reduce 遍历您的输入数组并为每个元素调用回调。这个回调有两个参数,第一个是上次迭代的输出,第二个是当前数组项。

这里的回调返回一个新的数组,该数组由之前的回调结果(使用扩展运算符...传播到新数组中)和当前项重复两次组成。

要开始减少过程,我们还需要一个初始值,这里我们给一个空数组,(reduce 的最后一个参数)。

这里对回调中accx的值进行详细说明,用于以下归约:

['a', 'b', 'c'].reduce((acc, x) => ([...acc, x, x]), []);
  1. acc = [], x = 'a' =&gt; returns ['a', 'a']
  2. acc = ['a', 'a'], x = 'b' =&gt; returns ['a', 'a', 'b', 'b']
  3. acc = ['a', 'a', 'b', 'b'], x = 'c' =&gt; returns ['a', 'a', 'b', 'b', 'c', 'c']

【讨论】:

  • 如您所见,用户是编程新手。在回答中添加解释会对操作和未来的读者产生疑问。
  • 谢谢,这是一个好点,我会添加更多的解释
【解决方案2】:
  • 使用.map() 迭代input 数组。
  • 使用Array() 构造函数初始化新数组,并使用数组的.fill() 方法填充它。
  • 最后,您可以使用.concat() 和展开运算符将数组数组转换为单个数组。

const input = ['onions', 'tomatoes', 'garlic', 'fontina'];

const dupeValues = (arr, factor) => [].concat(...arr.map(s => new Array(factor).fill(s)));

console.log(dupeValues(input, 2));
console.log(dupeValues(input, 3));

【讨论】:

  • 如您所见,用户是编程新手。在答案中添加解释会给操作和未来的读者带来奇迹。
  • 非常感谢大家的帮助。我从每个回复中都学到了很多东西,并将它与 array.reduce() 和传播运算符一起使用...感谢您的宝贵时间...跨度>
  • 为了保持通用性+1
【解决方案3】:

使用Array.flatMap()(IE/Edge 不支持):

const array = ['onions', 'tomatoes', 'garlic', 'fontina'];

const result = array.flatMap(item => [item, item]);

console.log(result)

【讨论】:

    【解决方案4】:

    使用原生 JavaScript:

    const ingredients = [ 'onions', 'tomatoes', 'garlic', 'fontina' ]
    const ingredientsToRemove = [ 'onions', 'red pepper' ]
    
    // Using Array.reduce method
    const doubleIngredients = ingredients.reduce(
      ( array, ingredient ) =>
      {
        // If the ingredient has to be removed, return the array
        // Else return the array with two times the current ingredient
        return ingredientsToRemove.includes( ingredient ) ?
          array
          :
          [ ...array, ingredient, ingredient ]      
      },
      []
    )
    
    console.log({ ingredients, doubleIngredients })

    【讨论】:

      【解决方案5】:

      这里的问题是

      string * 2 不会返回 2 个字符串给您。它将返回NaN

      console.log('test'* 2) //NaN

      您想要实现的目标可以通过repeat 方法完成。

      console.log('test '.repeat(2))

      你的预期输出可以这样实现

      let arr = ['onions', 'tomatoes', 'garlic', 'fontina']
      let output = arr.reduce((op,inp)=>(op.concat([inp,inp])),[])
      console.log(output)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-06
        相关资源
        最近更新 更多