Javascript 内爆阵列未按预期工作
看看我的代码:Javascript 内爆阵列未按预期工作,javascript,jquery,arrays,join,Javascript,Jquery,Arrays,Join,看看我的代码: // is_array function function is_array(input){ return typeof(input)=='object'&&(input instanceof Array); } // Check if cos_in is an array. If is not, create him if(!is_array(cos_in)) { var cos_in = new Array(); } // Onclick func
// is_array function
function is_array(input){ return typeof(input)=='object'&&(input instanceof Array); }
// Check if cos_in is an array. If is not, create him
if(!is_array(cos_in))
{
var cos_in = new Array();
}
// Onclick function
function cos(pret,box,configuratie)
{
// Create a value (is different on every click; using different box)
cos_in[box] = box + '|||' + pret + '|||' + configuratie + '||||';
// Insert values from array in some div with #cos id
$("#cos").html(cos_in.join('||||'));
}
我的问题是id为#cos的div的起始值为“testempty”,每次执行onclick函数时,div都应该有from函数的值。但是is返回一个空div
请提供一些帮助?虽然此代码可以改进很多,但我已尝试解决您的第一个直接问题 是否要在每次单击时追加结果?在哪里加入? 您是想连接键还是值?我假设您现在想要的是值而不是键
window.cos_in = window.cos_in && window.cos_in instanceof Array ? window.cos_in : []
// Onclick function
function cos(pret,box,configuratie)
{
// Create a value (is different on every click; using different box)
cos_in.push(box + '|||' + pret + '|||' + configuratie + '||||');
// Insert values from array in some div with #cos id
$("#cos").html(cos_in.join('||||'));
}
让我重复一下,以获得可读/可理解的内容
这是你正在做的事情的清洁工。为了进一步改进,我需要知道你的链接和参数要去哪里
var cos = (function (cos_in) {
return function cos(pret, box, configuratie) {
// Create a value (is different on every click; using different box)
cos_in.push(box + '|||' + pret + '|||' + configuratie + '||||');
// Insert values from array in some div with #cos id
$("#cos").text(cos_in.join('||||'));
};
}([]));
这是一个对象版本而不是数组的示例
var cos = (function (cos_in) {
return function cos(pret, box, configuratie) {
// Create a value (is different on every click; using different box)
cos_in[box] = (box + '|||' + pret + '|||' + configuratie + '||||');
// Insert values from array in some div with #cos id
$("#cos").text(Object.keys(cos_in).join('||||'));
};
}({}));
这是一个可以使用的简单包装器:
function join(input, str) {
if(typeof(input) === 'object') {
if(input instanceof Array) {
return input.join(str);
} else {
var tmp = [];
for(var x in input) {
if(input.hasOwnProperty(x)) {
tmp.push(input[x]);
}
}
return tmp.join(str);
}
}
return input;
}
/* ... */
$("#cos").html( join(cos_in, '||||') );
但是,您确实需要区分不同的语言。JavaScript可能不会像您预期的那样工作,至少与PHP相比是这样。您能提供一个演示和一个输入输出示例(以及所需的输出)吗?否则很难理解问题是什么。您提供的信息越多,我们就越容易帮助您,我们可以为您提供更好的解决方案。非常感谢。当然:啊,好的。。。。问题是,
box
是一个字符串,数组只能使用数字键。因此,cos_in.join(…)
返回一个空字符串。我不太确定这个函数的目的是什么,所以我不知道该给出什么建议。如果你真的需要连接“数组”中的所有元素,你必须使用一个对象,迭代并手动连接这些值。在php工程中。谢谢我发现这个主题:是的,似乎我需要使用对象而不是数组。但是仍然不起作用:(@ZadyPenelopa:它不起作用,因为没有任何东西像对象.prototype.join
。你不能使用特定于数组的函数,该函数在对象上使用长度属性和整数索引。我感谢你的回答。我将使用Bart Riemens的建议。