如何以指定的方式动态创建数组

时间:2016-10-21 05:28:13

标签: javascript jquery node.js

我有多个来自数据库的值,它随着添加新记录而增加。

我正在制作这样的跨度:

<span style="display:none;" class="skills"  data-skill="php programing">350</span>

<span style="display:none;" class="skills"  data-skill="java programing">235</span>

<span style="display:none;" class="skills"  data-skill="python programing">289</span>

我想以这种方式构建一个数组

var data = google.visualization.arrayToDataTable([
          ['jobs', 'Jobs Available'],
          ['php programing',     350],
          ['java programing',     235],
          ['python programing',  289]
        ]);

这样我就可以动态构建谷歌饼图

现在我正在做这样的事情

arrayToDataTable = [];
arrayTemp = [];
$.each('.skills',function(i){
 var skill = $(this).data('skill');
 var number = $(this).text();
  arrayTemp.push(skill);
  arrayTemp.push(number);
  arrayToDataTable.push(arrayTemp);
});


**my question how can i make array in this fashion dynamically:**

     [
          ['jobs', 'Jobs Available'],
          ['php programing',     350],
          ['java programing',     235],
          ['python programing',  289]
       ]

请提前帮助我

2 个答案:

答案 0 :(得分:2)

arrayToDataTable = [];

$.each('.skills',function(i){
 var skill = $(this).data('skill');
 var number = $(this).text();
  arrayToDataTable.push([skill, number]);
});

console.log(arrayToDataTable);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span style="display:none;" class="skills"  data-skill="php programing">350</span>

<span style="display:none;" class="skills"  data-skill="java programing">235</span>

<span style="display:none;" class="skills"  data-skill="python programing">289</span>

你试过了吗?

arrayToDataTable.push([arrayTemp])

答案 1 :(得分:2)

使用正确的每种语法,现在你的arrayTemp是全局定义的,所以你不断添加元素

尝试以下方法:

arrayToDataTable = [['jobs', 'Jobs Available']];

$('.skills').each(function(){
 var arrayTemp = [];//local variable
 var skill = $(this).data('skill');
 var number = $(this).text();
  arrayTemp.push(skill);
  arrayTemp.push(number);
  arrayToDataTable.push(arrayTemp);
});

演示:https://jsfiddle.net/uqxm0kf3/

或:

&#13;
&#13;
 arrayToDataTable = [['jobs', 'Jobs Available']];
        
        $('.skills').each(function(){
    
         var skill = $(this).data('skill');
         var number = $(this).text();
          arrayToDataTable.push([skill,number]);
        });
console.log(arrayToDataTable);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span style="display:none;" class="skills"  data-skill="php programing">350</span>

<span style="display:none;" class="skills"  data-skill="java programing">235</span>

<span style="display:none;" class="skills"  data-skill="python programing">289</span>
&#13;
&#13;
&#13;