简体   繁体   English

在 javascript 中编写一个接受任意数量的 object 的 function

[英]write a function that accepts any number of object in javascript

I know the implementation of how to pass infinite parameters in a function in javascript.我知道如何在 javascript 中的 function 中传递无限参数的实现。

But how to accepts any number of objects as a parameter in function?但是如何在 function 中接受任意数量的对象作为参数?

I have this:我有这个:

function merge<T>(objA:T, objB: T){
  return Object.assign(objA, objB);
}

so that I can do like this:这样我就可以这样做:

console.log(`${mergeObject2.age},  ${mergeObject2.name}`);

But how to declare a function if that number of objects is not known..?但是,如果不知道对象的数量,如何声明 function ..?

for example this:例如这个:

const mergeObject2 = merge({name: 'Niels'}, {age :39}, {hobby: 'all'});

Thank you.谢谢你。

so if I do it like this:所以如果我这样做:

const mergeObject2 = merge({name: 'Niels'}, {age :39} );

console.log(`${mergeObject2.age},  ${mergeObject2.name}`);

then the output is of course:那么 output 当然是:

39, Niels 39、尼尔斯

But how to do it if you have more objects..?但是如果你有更多的对象怎么办..?

Fundamentally, if you want to accept N parameters in TypeScript, the varying parameters will all have to have the same type.从根本上说,如果您想在 TypeScript 中接受N个参数,则不同的参数都必须具有相同的类型。 (It can be a union type, though.) For instance: (不过,它可以是联合类型。)例如:

function myFunction(a: boolean, b: string, ...rest: Array<number | string>) {
    // ...
}

( Array<number | string> can also be written (number | string)[] .) Array<number | string>也可以写成(number | string)[] 。)

That function requires at least two arguments (a boolean and a string ) followed by any number of number or string arguments. function 至少需要两个 arguments(一个boolean和一个string )后跟任意数量的numberstring ZDBC116FB4A5BDA28E7D777。 Note how the "rest" of the parameters are bundled up in an array, which is why they have to have the same type ( number | string in the example).请注意参数的“其余”是如何捆绑在一个数组中的,这就是为什么它们必须具有相同的类型(在示例中为number | string )。 Of course, once you're dealing with one specific element from that array, you can use if to narrow its type.当然,一旦您处理了该数组中的一个特定元素,您就可以使用if来缩小其类型。

If you don't need any fixed parameters ( a and b in the example), just start with the rest parameter.如果您不需要任何固定参数(示例中的ab ),只需从 rest 参数开始。

If you want to use Object.assign in the implementation, you'll need to make the first one required (or hardcode Object.assign 's first argument).如果您想在实现中使用Object.assign ,则需要使第一个成为必需(或硬编码Object.assign的第一个参数)。 So your merge might be:所以你的merge可能是:

function merge<T extends object>(target: T, ...sources: T[]): T {
    return Object.assign(target, ...sources);
}
const mergeObject2 = merge({name: "Niels"}, {age: 39}); // ¹
console.log(`${mergeObject2.age},  ${mergeObject2.name}`);

Playground link 游乐场链接

That's basically just Object.assign but with the types slightly more restricted (I think), though.这基本上只是Object.assign但类型稍微受限制(我认为)。


¹ You might want to put a {} at the beginning to avoid modifying the {name: "Neils"} object. ¹ 您可能需要在开头放置一个{}以避免修改{name: "Neils"} object。

You can make use of arguments object available in ES5.您可以使用 ES5 中提供的 arguments object。 It's just like a variable with type array, and is accessible inside a function.它就像一个数组类型的变量,可以在 function 中访问。 It contains the values of all the arguments passed to that function.它包含传递给该 function 的所有 arguments 的值。

function a(){
  let sum = 0;
  for(let i=0;i<arguments.length;i++){
    sum += arguments[i];
  }
  console.log(sum);
}
a(1,2,3);

In your case to copy all objects into one, you can do something like this:在您将所有对象复制到一个的情况下,您可以执行以下操作:

function a(){
  let finalObj = {};
  for(let i=0;i<arguments.length;i++){
    finalObj = {...finalObj,...arguments[i]};
  }
  console.log(finalObj);
}
a({id:1},{name:"sam"},{age: 25});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 编写一个接受参数和对象的jQuery函数 - write a jquery function which accepts params and object javascript对象属性类型仅接受数字 - javascript object property type accepts only number 限制Javascript函数接受的参数数量 - Limit Number of Parameters a Javascript Function Accepts 如何编写一个接受和“转发”可变数量参数的JS函数? - How to write a JS function that accepts and “forwards” variable number of parameters? 我如何编写一个接受 10 个字母的字符串并在 Javascript 中返回相应电话号码字符串的 function? - How do i write a function that accepts a 10-character string of letters and returns a corresponding phone number string in Javascript? 接受对象并从该对象返回title属性值的javascript函数 - javascript function that accepts an object and returns the value of the title property from that object JavaScript - 接受字符串和索引(数字)并返回该索引处的字符的函数 - JavaScript - function which accepts a string and an index (number) and returns the character at that index 如何知道 JavaScript function 接受一个简单的参数或一个解构的 object? - How to know a JavaScript function accepts a simple parameter or a destructured object? JavaScript:创建一个接受数组和回调的函数groupBy,并返回一个对象 - JavaScript: Create a function groupBy that accepts an array and a callback, and returns an object 编写一个函数,删除给定对象上的任何属性,其值是长于给定数字的字符串,并返回该对象 - Write a function that removes any properties on the given object whose values are strings longer than the given number and returns the object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM