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
中的每个条目,它是否是对象而不是未定义的;如果未定义,则必须抛出错误。我还必须检查至少有两个参数。
答案 0 :(得分:1)
g++
中的length
来检查Object.keys
。 {}
是Boolean({})
。true
检查includes()
包含args
还是null
undefined
和some()
检查数组的所有元素是否都是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)