我试图找出最好和最干净/简洁的方法来首先检查一个对象是否甚至具有任何值,如果是,则其中一个值是71

本质上,如果对象是empty,则函数应返回true。同样,如果函数不是empty而是包含71作为值之一(它们被数字索引),则它应该为true。其他一切都是假的。

我目前拥有的东西可以正常工作,但看起来有点混乱和冗长:

facets是对象

if (Object.keys(facets).length === 0) {
  if (facets[index] == 71) {
    return true;
  } else {
    return false;
  }
}

最佳答案

如果知道索引,请检查索引是否包含该值,如果不包含,请检查其是否为空:



const has = (obj, index, value) => obj[index] === 71 || !Object.keys(obj).length;

const index = 2;
const value = 71;

console.log('empty: ', has({}, index, value));
console.log('contains 71: ', has({ 1: 13}, index, value));
console.log('contains 71: ', has({ 1: 13, 2: 71 }, index, value));







如果不知道索引,则可以使用Object#keys提取键,检查length是否为0(!values.length),如果不知道,则使用Array#findIndex来查看对象是否包含请求值:



const facets = { 1: 0, 2: 71 };

const has = (obj, value) => {
  const keys = Object.keys(obj);
  return !keys.length || keys.findIndex((key) => obj[key] === value) !== -1;
}

const value = 71;

console.log('empty: ', has({}, value));
console.log('contains 71: ', has({ 1: 13}, value));
console.log('contains 71: ', has({ 1: 13, 2: 71 }, value));







索引未知时的另一种选择是使用Object#values

注意:Object#values不是ECMAScript2015(ES6)的一部分,而是ECMAScript2017中的草稿,并且仅受Chrome和Firefox支持。

使用Object#values提取值,检查length是否为0(!values.length),如果不是,则使用Array#includes查看values是否包含请求值。



const facets = { 1: 0, 2: 71 };

const has = (obj, value) => {
  const values = Object.values(obj);
  return !values.length || values.includes(value);
}

const value = 71;

console.log('empty: ', has({}, value));
console.log('contains 71: ', has({ 1: 13}, value));
console.log('contains 71: ', has({ 1: 13, 2: 71 }, value));

关于javascript - 检查两者是否为空或Javascript对象中是否包含值(ES2015),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41104775/

10-12 03:32
查看更多