如何正确使用javascript内置的参数? [英] How to make use of javascript built in arguments properly?

查看:90
本文介绍了如何正确使用javascript内置的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

在for循环中获取参数值:arguments [i]。那么如何将这个值分配给一个键呢?

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 log below, gives all values



                    console.debug(arguments[i]);




但我需要将每个值分配给如下所示的键。我怎么做
拜托?

but I need to assign each value to a key like below. How an I do that please?



                      mappedData.push({

                        'id': arguments[0],
                        'name': arguments[1],
                        'text': arguments[2],
                        'notification': arguments[3],
                        'lastseen': arguments[4],
                        'avatar': arguments[5]
                    });
                }


            },




我自己找到了答案,即删除
map函数中的for循环。这样我可以访问参数[1]并将其分配给

I found the answer by myself, which is to remove the for loop inside map function. That way I can access arguments[1] and assign it to the key

但我不知道是否有比这更好的答案,而不必用索引调用每个参数

But I don't know if there's a better answer than this, without having to call each argument with index

推荐答案

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

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内置的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆