如何正确使用javascript内置参数

How to make use of javascript built in arguments properly?

本文关键字:内置 参数 javascript 何正确      更新时间:2023-09-26

每个函数传递的参数数量是不确定的。因此我使用了参数对象。现在的问题是,我需要在压入数组时为每个值分配一个键。

arguments的值在for循环中像这样获得:arguments[i]。那么如何将这些值分配给一个键呢?

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]
                    });
                }

            },

我自己找到了答案,那就是删除里面的for循环地图功能。这样我就可以访问参数[1]并将其赋值给关键

但是我不知道是否有比这更好的答案,不需要调用index

您可以将arguments设置为spread元素后的表达式,以扩展arguments作为源可迭代对象的属性。返回目标作为数组中对象的属性。

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);

我的意思是,

function map(){
                var mappedData = [];
                var obj = {};
                for (var i = 0; i < arguments.length; i++)
                {
                    console.log(i + " "+ arguments[i]);
                    if (i % 6 == 0)
                        obj.id = arguments[i];
                    if (i % 6 == 1)
                        obj.name = arguments[i];
                    if (i % 6 == 2)
                        obj.text = arguments[i];
                    if (i % 6 == 3)
                        obj.notification = arguments[i];
                    if (i % 6 == 4)
                        obj.lastseen = arguments[i];
                    if (i % 6 == 5)
                    {
                        obj.avatar =arguments[i];
                        mappedData.push(obj);
                        obj = {};
                    }
                    if(i+1 == arguments.length &&  (i % 6 != 5))
                    {
                        mappedData.push(obj);
                    }
                }
                        return mappedData;
            }

我看不出这样做背后的逻辑。如果传递的参数将在预定的对象中使用,为什么不向函数传递一个opts形参呢?

map: function(opts){
  var mappedData = []
  mappedData.push(opts)
}

称之为:

map({ ... })

当传递给函数的参数不需要函数正常工作时,应使用

arguments参数