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

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

问题描述

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

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


            },

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

解决方案

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天全站免登陆