js判断数组对象或对象对象数组是否包含元素包含值 并获取下标
单纯判断是否包含
var arr = [ { key:1, name: '牛百叶' }, { key:2, name: '虾滑' } ]; // bool 为true说明数组中包含这个对象 为false则不包含 var bool1 = arr.some(item=> item.name == '虾滑') var bool2 = arr.some(item=> item.name == '精品肥牛') console.log(bool1) // true console.log(bool2) // false
获取下标
var array = [1,2,3,'4']; var indexOf4 = (array || []).findIndex((item) => item === '4'); console.log(indexOf4); // 3 var profiles= [ { id: 'id123', name: "lin", age: 23 }, { id: 'id456', name: "lin2", age: 12 }, { id: 'id678', name: "lin3", age: 13 } ]; var currentProfile = { id: 'id456', name: "lin2", age: 12 }; var currentProfileIndex = (profiles|| []).findIndex((profile) => profile.id === currentProfile .id); console.log(currentProfileIndex );