如果我有以下对象数组:
[ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
是否有一种方法通过数组循环检查特定的用户名值是否已经存在,如果它不做任何事情,但如果它没有添加一个新对象到数组的用户名(和新ID)?
谢谢!
如果我有以下对象数组:
[ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
是否有一种方法通过数组循环检查特定的用户名值是否已经存在,如果它不做任何事情,但如果它没有添加一个新对象到数组的用户名(和新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 }); }
}
其他回答
下面是一个ES6方法链,使用.map()和.includes():
const arr = [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
const checkForUser = (newUsername) => {
arr.map(user => {
return user.username
}).includes(newUsername)
}
if (!checkForUser('fred')){
// add fred
}
映射现有用户以创建用户名字符串数组。 检查该用户名数组是否包含新用户名 如果不存在,则添加新用户
你可以建立你的数组原型,使它更模块化,尝试这样的东西
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)
请看下面的例子
$(document).ready(function(){ const arr = document.querySelector(".list"); var abcde = [{ id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' }]; $("#btnCheckUser").click(function() { var tbUsername = $("#tbUsername").val(); if (abcde.some(obj => obj.username === tbUsername)) { alert('existing user ' + tbUsername); return; } else { abcde.push({ id: abcde.length + 1, username: tbUsername }); alert('added new user ' + tbUsername); arr.appendChild(createArray(tbUsername)); return; } }); function createArray(name) { let li = document.createElement("li"); li.textContent = name; return li; } abcde.forEach((x) => arr.appendChild(createArray(x.username))); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <p>Add text and click on Check.</p> <input type="text" id="tbUsername" /> <button type="button" id="btnCheckUser">Check</button> <div class="list"> <ul></ul> </div>
我喜欢Andy的回答,但是id不一定是唯一的,所以这里是我想出的创建唯一id的方法。也可以在jsfiddle上查看。请注意arr。如果之前已经删除了任何内容,length + 1可能无法保证唯一的ID。
var array = [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' } ];
var usedname = 'bill';
var newname = 'sam';
// don't add used name
console.log('before usedname: ' + JSON.stringify(array));
tryAdd(usedname, array);
console.log('before newname: ' + JSON.stringify(array));
tryAdd(newname, array);
console.log('after newname: ' + JSON.stringify(array));
function tryAdd(name, array) {
var found = false;
var i = 0;
var maxId = 1;
for (i in array) {
// Check max id
if (maxId <= array[i].id)
maxId = array[i].id + 1;
// Don't need to add if we find it
if (array[i].username === name)
found = true;
}
if (!found)
array[++i] = { id: maxId, username: name };
}
数组的本地函数有时比普通循环慢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>
这样你可以更快地达到目的。
注意:我没有检查传递的参数是否为空,如果你想,你可以对它进行检查或写一个正则表达式进行特定的验证。