如何检查通过rest参数传递的对象是否为null或未定义?

时间:2019-02-20 06:46:52

标签: javascript

function extend(...args),如果我运行该函数并在其中传递空对象

function extend({}),如何检查它是否为空或未定义。

输入:const first = { x: 2, y: 3}; const second = { a: 70, x: 4, z: 5 }; const third = { x: 0, y: 9, q: 10 }; const firstSecondThird = extend(first, second, third);

预期输出:{ x: 2, y: 3, a: 70, z: 5, q: 10 } 我还必须检查...args中的每个条目,它是否是对象而不是未定义的;如果未定义,则必须抛出错误。我还必须检查至少有两个参数。

2 个答案:

答案 0 :(得分:1)

  • 您可以检查g++中的length来检查Object.keys{}Boolean({})
  • 使用true检查includes()包含args还是null
  • 使用undefinedsome()检查数组的所有元素是否都是typeof
  • 您不希望您的属性在出现两次时被覆盖。然后,您可以object

reverse()

最重要的是,if语句可以组合为一个语句。

答案 1 :(得分:0)

您可以为预期的输出实现它。

const first = { x: 2, y: 3 }; 
const second = { a: 70, x: 4, z: 5 };  
const third = { x: 0, y: 9, q: 10 };
const fourth = undefined;

const firstSecondThird = extend(first, second, third, fourth);

function extend (...args) {
    let result = Object.assign({}, ...args.reverse()); 
    if (result.length < 2) throw ("Length is less than 2");
    if (args.includes(undefined) || args.includes(null)) throw ("args contains undefined")
    return result;
}

console.log(firstSecondThird)

const first = { x: 2, y: 3 }; 
const second = { a: 70, x: 4, z: 5 };  
const third = { x: 0, y: 9, q: 10 };

const firstSecondThird = extend(first, second, third);

function extend (...args) {
    let result = Object.assign({}, ...args.reverse()); 
    if (result.length < 2) throw ("Length is less than 2");
    if (args.includes(undefined) || args.includes(null)) throw ("args contains undefined")
    return result;
}

console.log(firstSecondThird)