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'}
其他方法