问题描述
每个函数传递的参数个数是不确定的.因此我正在使用参数对象.现在的问题是,我需要在推送到数组时为每个值分配一个键.
arguments 值在 for 循环中是这样获得的:arguments[i].那么如何将每个值分配给一个键?
map: function() {var 映射数据 = [];for (var i = 0; i < arguments.length; i++) {
控制台日志如下,给出所有值
console.debug(arguments[i]);
但我需要将每个值分配给如下所示的键.我是怎么做的好吗?
mappingData.push({'id':参数[0],名称":参数[1],'文本':参数[2],'通知':参数[3],'lastseen':参数[4],'头像':参数[5]});}},
我自己找到了答案,就是去掉里面的for循环地图功能.这样我就可以访问参数 [1] 并将其分配给键
但我不知道是否有比这更好的答案,而不必用索引调用每个参数
您可以使用解构赋值并将 arguments
设置为 spread
元素之后的表达式来扩展 arguments
作为源可迭代.将目标作为数组中对象的属性返回.
function map() {让 [id, name, text, validation, lastseen, avatar] = [...arguments];让mappedData = [{id, name, text, validation, lastseen, avatar}];返回映射数据}let res = map("a", "b", "c", "d", "e", "f");console.log(res);
the number of parameters passed by each function is uncertain. Therefore I'm making use of arguments object. Now the problem is,I need to assign each value a key while pushing to an array.
arguments value is obtained like this inside for loop: arguments[i]. So how to assign each of this value to a key?
map: function() {
var mappedData = [];
for (var i = 0; i < arguments.length; i++) {
console.debug(arguments[i]);
mappedData.push({
'id': arguments[0],
'name': arguments[1],
'text': arguments[2],
'notification': arguments[3],
'lastseen': arguments[4],
'avatar': arguments[5]
});
}
},
But I don't know if there's a better answer than this, without having to call each argument with index
You can use destructuring assignment with arguments
set to expression following spread
element to expand properties of arguments
as source iterable. Return targets as properties of an object within an array.
function map() {
let [id, name, text, validation, lastseen, avatar] = [...arguments];
let mappedData = [{id, name, text, validation, lastseen, avatar}];
return mappedData
}
let res = map("a", "b", "c", "d", "e", "f");
console.log(res);
这篇关于如何正确使用内置参数的javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!