增加Javascript数组中项的值

时间:2018-03-19 16:56:08

标签: javascript arrays

我有Javascript数组,如下所示:

 fruitsGroups: [
    "apple0",
    "banana0",
    "pear0",
  ]

如何增加此数组中每个项目的数量?

 fruitsGroups: [

    "apple0",
    "apple1",
    "apple2",

    "banana0",
    "banana1",
    "banana2",

    "pear0",
    "pear1",
    "pear2"
  ]

5 个答案:

答案 0 :(得分:1)

我认为你在寻找类似的东西?

var fruitsGroups = [
    "apple0",
    "banana0",
    "pear0",
  ];
  console.log(fruitsGroups);

  var newFruits = [];
  $.each(fruitsGroups, function(i, j) {
     var n = parseInt(j.substring(j.length - 1));
     for(var k = 0; k < 3; k++) {
        newFruits.push(j.substring(0, j.length - 1) + (n + k));
     }
  });

  console.log(newFruits);

答案 1 :(得分:1)

您可以创建使用x方法的函数并返回新数组。

&#13;
&#13;
reduce()
&#13;
&#13;
&#13;

答案 2 :(得分:1)

由于我们已经有2018年,另一种方法是使用Array.map和destructuring:

const groups = [
    "apple0",
    "banana0",
    "pear0",
  ];

[].concat(...groups.map(item => [
    item,
    item.replace(0, 1),
    item.replace(0, 2)
  ]
))

// result: ["apple0", "apple1", "apple2",
//          "banana0", "banana1", "banana2",
//          "pear0", "pear1", "pear2"]

说明:

groups.map(item => [item, item.replace(0, 1), item.replace(0, 2)])逐个获取每个数组项(apple0,然后banana0,...)并将其替换为以下数组:

  • item - 项目本身(apple0
  • item.replace(0, 1) - 将零替换为1apple1
  • 的项目
  • item.replace(0, 2) - 将零替换为2apple2
  • 的项目

所以数组看起来像......

[
  ["apple0", "apple1", "apple2"],
  ["banana0", "banana1", "banana2"],
  ["pear0", "pear1", "pear2"],
]

...然后我们需要将其展平,即[].concat(...部分。它基本上采用数组项(三个点read more about destructuring here),并将它们合并为一个空数组。

如果要替换任何数字,而不仅仅是零,请使用正则表达式:

"apple0".replace(/\d$/, 1)
 // -> "apple1"
"apple9".replace(/\d$/, 1)
 // -> "apple1"
  • \d - 任何数字字符
  • $ - 行尾
  • 周围的斜线告诉JS它是一个正则表达式,你也可以使用new RegExp("\d$")

答案 3 :(得分:0)

我已经为你试过这个,根据我的理解,它可能会有所帮助。天真的方法

&#13;
&#13;
var a = ['apple0','banana0','pearl0']
var fruitGroups = []
for(var i=0; i < a.length; i++){
	for(var j = 0; j<a.length; j++){
  	let fruit = a[i].replace(/\d/g,'')+j
  	fruitGroups.push(fruit)
  }
}
console.log(fruitGroups)
&#13;
&#13;
&#13;

答案 4 :(得分:0)

Map原始数组。对于每个项目,创建一个子数组,并使用当前项目fill。然后用索引映射子数组和replace每个项目的数字/ s。将子数组按spreading展平为Array.concat()

const fruitsGroups = [
  "apple0",
  "banana0",
  "pear0",
];

const len = 3;
// map the original array, and use concat to flatten the sub arrays
const result = [].concat(...fruitsGroups.map((item) => 
  new Array(len) // create a new sub array with the requested size
  .fill(item) // fill it with the item
  .map((s, i) => s.replace(/\d+/, i)) // map the strings in the sub array, and replace the number with the index
));

console.log(result);