共计 1989 个字符,预计需要花费 5 分钟才能阅读完成。
通常须要查看值是否符合条件而且值在对象中,这里有一些办法,能够应用一些 () every () 和 Object.values ()来实现这一点
Object.values
Value 用于依据 Object 中的值创立数组。传递一个对象到 Object.values,它将返回一个值数组
const stock = {
meat: 5,
fruit: 10,
cheese: 6,
}
const valueArray = Object.values(stock)
// [5, 10, 6]
some()
如果依据传入的条件有一个符合条件,some ()返回 true。如果没有,它将返回 false
const stock = {
meat: 5,
fruit: 10,
cheese: 6,
}
const enoughStock = Object.values(stock).some(el => el >= 6)
console.log(enoughStock) // true
const kidsParty = {
suzy: 12,
bill: 4,
tim: 2,
sally: 5,
ming: 3,
}
const isAdultPresent = Object.values(kidsParty).some(el => el >= 18)
console.log(isAdultPresent) //false
every()
Every ()依据条件返回 true 或 false,如果每一项都符合条件
const nightclub = {
dave: 26,
sally: 23,
mike: 17,
lucy: 18,
}
const isOldEnough = Object.values(nightclub).every(el => el >= 18)
// false
if (!isOldEnough) {console.log("Check every ID")
}
检测数组中的每一项是否符合要求
const computers = [{name:"Apple",ram:8},
{name:"IBM",ram:4},
{name:"Acer",ram:32},
];
var result= computers.every(function(computer){return computer.ram > 16})
console.log(result)//false;
var some = computers.some(function(computer){return computer.ram > 16})
console.log(some)//true;
拓展 Object.entries()
Object.entries() 办法返回一个给定对象本身可枚举属性的 键值对数组 ,其 排列 与应用 for…in 循环遍历该对象时返回的程序统一(区别在于 for-in 循环也枚举 原型链中的属性
传入对象
const obj = {foo: 'bar', baz: 'abc'};
console.log(Object.entries(obj)); // [['foo', 'bar'], ['baz', 'abc']]
数组
const arr = [1, 2, 3];
console.log(Object.entries(arr)); // [['0', 1], ['1', '2'], ['2', '3']]
数组(数组中蕴含对象)
const arr1 = [{a: 1}, 2, 3];
console.log(Object.entries(arr1)); // [['0', { a: 1}], ['1', '2'], ['2', '3']]
数组(数组中的值全副为对象)
const arr2 = [{a: 1}, {b: 2}, {c: 3}];
console.log(Object.entries(arr2)); // [['0', { a: 1}], ['1', { b: 2}], ['2', { c: 3}]]
字符串
const str = '123';
console.log(Object.entries(str)); // [['0', '1'], ['1', '2'], ['2', '3']]
数字、浮点数
const num = 123;
console.log(Object.entries(num)); // []
const float1 = 12.3;
console.log(Object.entries(float1)); // []
将 Object 转化为 Map
new Map() 构造函数承受一个可迭代的 entries。借助 Object.entries 办法你能够很容易的将 Object 转换为 Map:
const obj2 = {foo: 'bar', baz: 'abc'};
console.log(Object.entries(obj2)); // [['foo', 'bar'], ['baz', 'abc']]
const map = new Map(Object.entries(obj2));
console.log(map); // Map {'foo' => 'bar', 'baz' => 'abc'}
其余办法
正文完
发表至: javascript
2020-10-21