2016-11-16 44 views
1

我有我的表有问题,我需要把几个变量在我的表,这是我的错误问题JS表

TypeError: tabproduit[i] is undefined

tabproduit[i][0] = $(this).text();

,这是我的代码

var tabproduit = new Array(new Array()); 
var i = 0 ; 
$(".eachnom").each(function(index) { 
    tabproduit[i][0] = $(this).text(); 
    i++; 
}); 

但是,当我不把i++;我没有错误,但我只有1变量在我的表;如何把这个i++;

在此先感谢

+1

使用'index'而不是'i'.Its也在每个函数调用中递增。像这样'tabproduit [index] [0]' – prasanth

+0

问题是你还没有显示你的html部分 – Mahi

回答

0

问题是你得到的错误,因为JS提供自然单维数组,你可以扩展它分为两个受以下约定维

var s = [[],[],[]] 

如果没有,那么你会得到阵列[ith]的位置总是未定义的

所以我给你的建议是首先得到行数然后定义

s [r1] = []; S [R2] = [] ...等,可以使用循环

,那么你就可以做S [R1] [C1]操作

希望它有助于

-2

这可以帮助您与您的代码:

ar tabproduit = new Array(new Array()); 

$(".eachnom").each(function(index) { 
    tabproduit[index][0] = $(this).text(); 
}); 
+0

虽然这可能回答这个问题,但向代码添加解释是一种很好的方式。 – BDL

1

无需i你已经从jQuery方法each()的景气指数,只是用它:

var tabproduit = new Array(new Array()); 

$(".eachnom").each(function(index) { 
    tabproduit[index][0] = $(this).text(); 
}); 

希望这会有所帮助。

+0

我总是有同样的错误: TypeError:tabproduit [index] is undefined tabproduit [index] [0] = $(this).text(); – weymeels

+0

你想要的'输出'是什么?你想如何让数组'tabproduit'看起来像。 –

0

变化tabproduit[0][index]

var tabproduit = new Array(new Array()); 
 

 
$(".eachnom").each(function (index) { 
 
    tabproduit[0][index] = $(this).text(); 
 
    
 
}); 
 
console.log(tabproduit)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<p class="eachnom">dcbmc</p> 
 
<p class="eachnom">cnc</p> 
 
<p class="eachnom">xcjx</p> 
 
<p class="eachnom">xmcn</p> 
 
<p class="eachnom">xcnx</p>

+0

它返回什么? '$(“.eachnom”)'?数组或对象如果数组然后什么数组感谢 – Mahi

+0

,像你一样工作,但我需要像这样tabiserit [index] [0] = $(this).text();并且它没有工作 – weymeels

+0

只是这样的产品的名称:FAUTEUIL RELEV AVALON G4 BEIG – weymeels

0

由于错误说“tabproduit [i]是未定义的”。您必须在循环内初始化tabproduit [i]。 尝试:

var tabproduit = new Array(new Array()); 
var i = 0 ; 
$(".eachnom").each(function(index) { 
console.log(index); 
tabproduit[i]= new Array(); 
    tabproduit[i][0] = $(this); 
    i++; 
}); 

PS:代替使用新的Array()是优选使用[];

0

这应该工作:

var tabproduit = []; 
var i = 0 ; 
$(".eachnom").each(function() { 
    tabproduit.push([$(this).text()]); 
    i++; 
}); 

但我认为你正在试图做的是这样的:

var tabproduit = []; 
var i = 0 ; 
$(".eachnom").each(function() { 
    tabproduit.push($(this).text()); 
    i++; 
}); 

嗯,这取决于你的阵列的实际结构。 干杯..!