如果我有以下对象数组:

[ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]

是否有一种方法通过数组循环检查特定的用户名值是否已经存在,如果它不做任何事情,但如果它没有添加一个新对象到数组的用户名(和新ID)?

谢谢!


当前回答

极大地简化了我之前的解决方案,并通过在检查指定ID是否存在之前无需遍历整个数组来提供更好的性能。

这应该是最简单的解决方案(我认为):

const users = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }];
const addUser = (username) => {
  const user = users.find((user) => user.username === username);
  if (user) return { ...user, new: false };
  const newUser = {
    id: users.length + 1,
    username,
  };
  users.push(newUser);
  return { ...newUser, new: true };
};

下面是一个活生生的例子:

const users = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }]; const addUser = (username) => { const user = users.find((user) => user.username === username); if (user) return { ...user, new: false }; const newUser = { id: users.length + 1, username, }; users.push(newUser); return { ...newUser, new: true }; }; // a little extra scripting here to support the input and button in the example const form = document.querySelector('form'); const input = document.querySelector('input'); const span = document.querySelector('span'); const pre = document.querySelector('pre'); const syncDataWithPre = () => { pre.innerHTML = JSON.stringify(users, null, 2); }; form.onsubmit = (e) => { e.preventDefault(); span.textContent = ''; if (input.value) { const user = addUser(input.value); const { new: isNew, ...userDetails } = user; span.classList[isNew ? 'add' : 'remove']('new'); span.textContent = `User ${isNew ? 'added' : 'already exists'}`; } input.value = ''; syncDataWithPre(); }; syncDataWithPre(); body { font-family: arial, sans-serif; } span { display: block; padding-top: 8px; font-weight: 700; color: #777; } span:empty { display: none; } .new { color: #0a0; } .existing: { color: #777; } <form> <input placeholder="New username" /> <button>Add user</button> </form> <span></span> <pre></pre>

其他回答

极大地简化了我之前的解决方案,并通过在检查指定ID是否存在之前无需遍历整个数组来提供更好的性能。

这应该是最简单的解决方案(我认为):

const users = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }];
const addUser = (username) => {
  const user = users.find((user) => user.username === username);
  if (user) return { ...user, new: false };
  const newUser = {
    id: users.length + 1,
    username,
  };
  users.push(newUser);
  return { ...newUser, new: true };
};

下面是一个活生生的例子:

const users = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' }]; const addUser = (username) => { const user = users.find((user) => user.username === username); if (user) return { ...user, new: false }; const newUser = { id: users.length + 1, username, }; users.push(newUser); return { ...newUser, new: true }; }; // a little extra scripting here to support the input and button in the example const form = document.querySelector('form'); const input = document.querySelector('input'); const span = document.querySelector('span'); const pre = document.querySelector('pre'); const syncDataWithPre = () => { pre.innerHTML = JSON.stringify(users, null, 2); }; form.onsubmit = (e) => { e.preventDefault(); span.textContent = ''; if (input.value) { const user = addUser(input.value); const { new: isNew, ...userDetails } = user; span.classList[isNew ? 'add' : 'remove']('new'); span.textContent = `User ${isNew ? 'added' : 'already exists'}`; } input.value = ''; syncDataWithPre(); }; syncDataWithPre(); body { font-family: arial, sans-serif; } span { display: block; padding-top: 8px; font-weight: 700; color: #777; } span:empty { display: none; } .new { color: #0a0; } .existing: { color: #777; } <form> <input placeholder="New username" /> <button>Add user</button> </form> <span></span> <pre></pre>

数组的本地函数有时比普通循环慢3 - 5倍。另外,本地函数在所有浏览器中都不能工作,所以存在兼容性问题。

我的代码:

<script>
  var obj = [];

  function checkName(name) {
    // declarations
    var flag = 0;
    var len = obj.length;   
    var i = 0;
    var id = 1;

    // looping array
    for (i; i < len; i++) {
        // if name matches
        if (name == obj[i]['username']) {
            flag = 1;
            break;
        } else {
            // increment the id by 1
            id = id + 1;
        }
    }

    // if flag = 1 then name exits else push in array
    if (flag == 0) {
      // new entry push in array        
      obj.push({'id':id, 'username': name});
    }
  }
  // function end

  checkName('abc');
</script>

这样你可以更快地达到目的。

注意:我没有检查传递的参数是否为空,如果你想,你可以对它进行检查或写一个正则表达式进行特定的验证。

检查现有的用户名相当简单:

var arr = [{ id: 1, username: 'fred' }, 
  { id: 2, username: 'bill'}, 
  { id: 3, username: 'ted' }];

function userExists(username) {
  return arr.some(function(el) {
    return el.username === username;
  }); 
}

console.log(userExists('fred')); // true
console.log(userExists('bred')); // false

但是当你必须向这个数组中添加一个新用户时,要做什么就不那么明显了。最简单的方法-只是推入一个id等于array的新元素。长度+ 1:

function addUser(username) {
  if (userExists(username)) {
    return false; 
  }
  arr.push({ id: arr.length + 1, username: username });
  return true;
}

addUser('fred'); // false
addUser('bred'); // true, user `bred` added

它将保证id的唯一性,但如果将一些元素从数组末尾删除,则会使该数组看起来有点奇怪。

接受的答案也可以这样写,在。some上使用箭头函数

 function checkAndAdd(name) {
     var id = arr.length + 1;
     var found = arr.some((el) => {
           return el.username === name;
     });
     if (!found) { arr.push({ id: id, username: name }); }
 }

你可以建立你的数组原型,使它更模块化,尝试这样的东西

    Array.prototype.hasElement = function(element) {
        var i;
        for (i = 0; i < this.length; i++) {
            if (this[i] === element) {
                return i; //Returns element position, so it exists
            }
        }

        return -1; //The element isn't in your array
    };

你可以这样使用它:

 yourArray.hasElement(yourArrayElement)