本文介绍了如何正确使用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.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

推荐答案

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

10-20 17:35