[英]How to check the objects passed through rest parameter are null or undefined?
function extend(...args)
, if I run the function and pass a null object in this function extend(...args)
,如果我运行该函数并在此传递一个空对象
function extend({})
, how to check if this is null or undefined. function extend({})
,如何检查这是 null 还是 undefined。
Input: const first = { x: 2, y: 3};
输入:
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);
Expected Output: { x: 2, y: 3, a: 70, z: 5, q: 10 }
I must also check that for each entry in ...args
, that it is an object and not undefined;预期输出:
{ x: 2, y: 3, a: 70, z: 5, q: 10 }
我还必须检查...args
每个条目,它是一个对象而不是未定义的; if any are undefined, it must throw an error.如果有任何未定义,则必须抛出错误。 I must also check that there are at least 2 arguments.
我还必须检查是否至少有 2 个参数。
length
of Object.keys
to check {}
.Object.keys
length
以检查{}
。 As Boolean({})
is true
.Boolean({})
是true
。includes()
to check whether args
contain null
or undefined
includes()
检查args
是否包含null
或undefined
some()
and typeof
to check if all the elements of array are object
.some()
和typeof
来检查数组的所有元素是否都是object
。reverse()
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([]));
The above all if statements can be combined as one statement.以上所有的 if 语句都可以合并为一个语句。
you can implement this for your expected output..你可以为你的预期输出实现这个..
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.