无法打印javascript数组值
在这里,内部document.write工作正常,但外部document.write打印未定义。无法打印javascript数组值,javascript,jquery,Javascript,Jquery,在这里,内部document.write工作正常,但外部document.write打印未定义。 P.S菜单项迭代后的值为4。有什么问题吗?问题是您在每次迭代时重置计数器(var i=0和var j=0) 只需使用带有索引的.each() var menu_items = 0; $(".trueol").each(function(){ menu_items = menu_items + 1; }); var product_price = new Array(menu_item
P.S菜单项迭代后的值为4。有什么问题吗?问题是您在每次迭代时重置计数器(
var i=0
和var j=0
)
只需使用带有索引的.each()
var menu_items = 0;
$(".trueol").each(function(){
menu_items = menu_items + 1;
});
var product_price = new Array(menu_items);
var product_name = new Array(menu_items);
$(".price").each(function(){
var i = 0;
product_price[i] = $(this).data("p");
document.write(product_price[i]); /*Inner document.write*/
i++;
});
document.write(product_price[2]); /*Outer document.write*/
$(".menu_product").each(function(){
var j = 0;
product_name[j] = $(this).text();
document.write(product_name[j]); /*Inner document.write*/
j++;
});
document.write(product_name[2]); /* Outer document.write */
尝试使用push()
// Arrays for your values
var product_price = [];
var product_name = [];
$(".price").each(function(index) {
product_price.push($(this).data("p"));
document.write(product_price[index]); /*Inner document.write*/
});
$(".menu_product").each(function(index) {
product_name.push($(this).text());
document.write(product_name[index]); /*Inner document.write*/
});
// Outer write
document.write(product_name[2]);
使用每个
迭代器的索引进行解释的答案是正确的,但是您将问题复杂化了。您只需将值推到数组的末尾,就可以忽略任何计数
var product_name = [],
product_price = [];
$(".price").each(function(){
t = $(this).data("p");
document.write(t); /*Inner document.write*/
product_price.push(t); // use push here
});
document.write(product_price[2]); /*Outer document.write*/
$(".menu_product").each(function(){
t = $(this).text();
document.write(t); /*Inner document.write*/
product_name.push(t); // use push here
});
document.write(product_name[2]); /* Outer document.write */
如果您需要知道数组中任意点的项数,只需使用
var product_price = [];
var product_name = [];
$(".price").each(function(){
var value = $(this).data("p");
product_price.push(value);
document.write(value); /*Inner document.write*/
});
document.write(product_price[2]); /*Outer document.write*/
$(".menu_product").each(function(){
var value = $(this).text();
product_name.push(value);
document.write(value); /*Inner document.write*/
});
document.write(product_name[2]); /* Outer document.write */
或
另一个提示。我假设您正在使用document.write
作为输出数据以进行调试的方法。尝试使用console.log(“文本”)改为编码>然后打开浏览器控制台(通常是F12并转到控制台选项卡)。这是一个范围问题。该函数中未正确定义产品名称。您需要仔细阅读变量范围。:)我认为你应该把var i=0和var j=0从循环中去掉。否则,它将始终将数据保存在位置0处的数组中increment@i-Conica:变量已定义,否则op将得到一个引用错误。显示完整的代码。。。而且小提琴会更好。。。!!是的,我又看了一遍,要么是被编辑了,要么是我觉得时间太早了。:)不客气-使用它比用不需要的东西污染DOM要好得多。
product_price.length
product_name.length