内爆阵列未按预期工作

Implode array not working as expected

本文关键字:工作 阵列      更新时间:2023-09-26

看看我的代码:

// 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 的起始值为"test-empty",并且每次执行 onclick 函数时,div 都应该具有函数的值。但是 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 相比是这样。