【问题标题】:Array push data from a parameter value [duplicate]数组从参数值推送数据[重复]
【发布时间】:2017-12-02 20:58:45
【问题描述】:

这是我到目前为止所做的

function setcanvas(ID,Count,Count1,Count2,Count3,Count4,Count5,Count6,Count7,Count8,Count9,Count10){
  var ctx = document.getElementById(ID).getContext('2d');
  ctx.canvas.width = 350;
  ctx.canvas.height = 300;
  var arr=[];
  var y=1;
  var str = "Count";
  while(y <= Count){
    var str2 = str + y;
    arr.push(str2);
    y++;
  }
}

我希望我的数组的值是参数上的值,但它不是。相反,我看到的值是 Count1、Count2、Count3 ...。有人可以向我解释一下吗?有什么方法可以实现这个目标吗?

找到解决方案

感谢下面的评论。我想出了这个解决方案。

  function setcanvas(ID,Count,Count1,Count2,Count3,Count4,Count5,Count6,Count7,Count8,Count9,Count10){
  var ctx = document.getElementById(ID).getContext('2d');
  ctx.canvas.width = 350;
  ctx.canvas.height = 300;
  var myBarChart = new Chart(ctx, {
    type: 'horizontalBar',
    data: {
        labels: ["Analytics 1", "Analytics 2", "Analytics 3", "Analytics 4", "Analytics 5"],
        datasets: [{
            label: "Count",
            data: getCountByArguments(Count1, Count2, Count3, Count4, Count5, Count6, Count7, Count8, Count9, Count10),
            backgroundColor: setUpBC(Count)
        }]
    },
    options: {}
  });

  function getCountByArguments(){
    var arr = [];
    var i=0; 
    while(i < Count) {
        arr.push(arguments[i]);
        i++;
    }
    return arr;
  }

 }

添加函数 getCountByArguments

【问题讨论】:

  • 使用可以使用arguments 对象来获取参数这可能会有所帮助stackoverflow.com/questions/4633125/…
  • 是的,str + y 不会神奇地让 Javascript 将其评估为变量。您想要的是变量变量,但在这种特定情况下,您应该查看arguments 对象。
  • 感谢大家,因为我知道了这个论点,我找到了解决方案

标签: javascript arrays array-push


【解决方案1】:

使用可以使用arguments 对象来获取参数,类似于下面的代码

function setcanvas(ID,Count,Count1,Count2,Count3,Count4,Count5,Count6,Count7,Count8,Count9,Count10){

  var arr=[];
for (var i=2; i < arguments.length; i++) {
        arr.push(arguments[i])
    }
    console.log(arr);
}

setcanvas(1,10,"a","b","c","d","e","f","g","h","i","j");

setcanvas(1,3,"a","b","c");

【讨论】:

  • 谢谢。但实际上由于某些技术原因,我不需要更改我的 setcanvas 的参数
  • 例如我改变了参数的数量,你可以尝试使用尽可能多的参数
  • 不,我的意思是我需要的参数数量由我的 setcanvas 中的参数 Count 决定。
  • 您可以根据 count 传递任意数量的参数,查看我编辑的答案
猜你喜欢
  • 2021-03-17
  • 1970-01-01
  • 2016-12-23
  • 1970-01-01
  • 2019-05-07
  • 2020-01-25
  • 2013-04-24
  • 2019-02-17
  • 2022-01-14
相关资源
最近更新 更多