function extend(...args)
,如果我运行该函数并在此传递一个null对象
function extend({})
,如何检查它是否为null或未定义。
输入: 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
,它是否是对象并且未定义;如果未定义,则必须抛出错误。我还必须检查至少有两个参数。
length
的Object.keys
检查{}
。照Boolean({})
原样true
。includes()
检查是否args
含有null
或undefined
some()
和typeof
检查array的所有元素是否都是object
。reverse()
function extend(...args){
if(args.length < 2) throw ("Length is less than 2");
if(!args.some(arg => typeof arg !== "object" || Object.keys(arg).length >=2 )) throw ("Arguments contain something other than object")
if(args.includes(undefined) || args.includes(null)) throw ("Arguments contain null or undefined");
else return Object.assign(...args.reverse())
}
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);
console.log(firstSecondThird)
console.log(extend({}));
console.log(extend(1,2,3, undefined));
console.log(extend(1,2,3, null));
console.log(extend([]));
以上所有if语句可以组合为一个语句。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句