Javascript:递增名称(如果存在)

时间:2019-03-17 08:35:40

标签: javascript jquery arrays ecmascript-5

我要在数组中推送一个名称,该名称将是默认名称。
如果名称已经存在,则需要在推送前为其添加一个整数,例如在实例已存在的情况下递增。

如果不存在,则应创建一个实例,在整个过程中将执行相同的操作,但应递增。

var arr = ['team banana', 'team melon', 'team melon 2', 'team orange'] 
var name = 'team apple'; // this is default team name
var xarr = [];

if(arr.length){
    // store the all instances of 'team apple'
    for(var c = 0; c <= arr.length; c++){
        if(arr[c] !== undefined){
            if(arr[c].indexOf('team apple')  > -1){
                xarr.push(arr[c].replace(/['0-9']/g,''))
            }
        }
    }
    // start the iterration
    for (var k=0; k<=arr.length; k++){
        // if existing
        if(arr[k] !== undefined){
            if(name === arr[k]) {
                arr.push(name+' ' + ( xarr.length))
            }else{
                // if not existing creat an instance of 'team apple'
                // arr.push(name) <--- this cause the browser to crash
            }
        }
    }
    xarr = []
}else{
    arr.push(name )
}

console.log(arr)

我期望的结果是这样的:

['team banana', 'team melon', 'team melon 2', 'team orange','team apple','team apple 1', 'team apple 2' ...]

该代码块已经在工作,除了如果阵列中没有“ team apple”实例,它开始崩溃

如果数组看起来像这样,则一切正常:

['team banana', 'team melon', 'team melon 2', 'team orange','team apple']

但是看起来像这样:

['team banana', 'team melon', 'team melon 2', 'team orange']

浏览器开始崩溃。

这是导致它的代码的一部分,我不知道。

if(name === arr[k]) {
    arr.push(name+' ' + (xarr.length))
}else{
    // if not existing creat an instance of 'team apple'
    // arr.push(name) <--- this cause the browser to crash
}

我什至不确定这是否是正确的实现方式,我真正想要的是一个递增的名称。任何建议都会有很大帮助。我也仅限于ES5。

预先感谢

2 个答案:

答案 0 :(得分:3)

仅使用过滤器并将结果长度作为后缀会容易得多。您的代码中有很多循环,只需要一个循环

const arr = ['team banana', 'team melon', 'team melon 2', 'team orange']
const name = 'team apple';

function addToArr(arr, name) {
  const postfix = arr.filter(e => e.replace(/\s\d+$/, '') === name).length || '';
  arr.push(`${name} ${postfix}`.trim());
  return arr;
}

console.log(addToArr(arr, name));
console.log(addToArr(arr, name));
console.log(addToArr(arr, name));

ES 5版本

var arr = ['team banana', 'team melon', 'team melon 2', 'team orange']
var name = 'team apple';

function addToArr(arr, name) {
  var postfix = arr.filter(function(e) { return e.replace(/\s\d+$/, '') === name}).length || '';
  arr.push((name + ' ' + postfix).trim());
  return arr;
}

console.log(addToArr(arr, name));
console.log(addToArr(arr, name));
console.log(addToArr(arr, name));

答案 1 :(得分:0)

您只需要确定要添加的团队实例的数量即可。为此,您可以使用Array.filtersee MDN)或您自己的过滤方法。像这样:

(() => {
  let arr = ['team banana', 'team melon', 'team melon 2', 'team orange'];
  const teamApple = "team apple";

  addTeam(teamApple, arr);
  addTeam(teamApple, arr);
  addTeam(teamApple, arr);
  addTeam(teamApple, arr);
  addTeamAlternative(teamApple, arr);
  console.log(arr);
  
  // will it work for an empty array?
  let newArr = [];
  addTeamAlternative(teamApple, newArr);
  addTeamAlternative(teamApple, newArr);
  addTeam("team kiwifruit", newArr);
  addTeam("team kiwifruit", newArr);
  console.log(newArr);
  
  // Array.filter and ES20xx
  function addTeam(team, someArr) {
    const nExisting = someArr.filter(teamFromArray => teamFromArray.startsWith(team)).length;
    someArr.push(team + (nExisting == 0 ? "" : ` ${nExisting + 1}`));
    return someArr;
  }
  
  // Your own method (a more 'classic' alternative)
  function addTeamAlternative(team, someArr) {
    var arrSearch = someArr.slice(0);
    var value = arrSearch.shift();
    var nExisting = 1;
    while(value) {
      nExisting += +RegExp("^" + team).test(value);
      value = arrSearch.shift();
    }
    someArr.push(team + (nExisting > 1 ? (" " + nExisting) : ""));
    return someArr;
  }
})()