如何在javascript

时间:2015-11-09 13:23:34

标签: javascript arrays

有人可以解决我的问题吗? 输入:

var input = [
    "a-b",
    "b-c",
    "c-d",
    "e-f"
];

输出

var output = [
    "a-d",
    "e-f"
];

1 个答案:

答案 0 :(得分:0)

出于此特定目的,您可以使用以下代码:



var input = [
    "a-b",
    "b-c",
    "c-d",
    "e-f",
    "j-k",
    "o-p",
    "p-q"
];
document.getElementById("input").innerHTML = "input: " + input;

function combineElements(array){
    var lastRange = array[0];
    var output = [];
    for(var index = 1; index < array.length; index++){
        if(lastRange[2] == array[index][0]){
            lastRange = lastRange.substring(0, 2) + array[index][2];
        }
        else{
            output.push(lastRange);
            lastRange = array[index];
        }
    }
    output.push(lastRange);
    return output;
}

document.getElementById("result").innerHTML = "output: " + combineElements(input);
&#13;
<p id="input"></p>
<p id="result"></p>
&#13;
&#13;
&#13;

或者如果你想要它更有活力(只检查最后和第一个字符):

&#13;
&#13;
var input = [
    "a-b",
    "b-c",
    "c-d",
    "e-f",
    "j-k",
    "o-p",
    "p-q"
];
document.getElementById("input").innerHTML = "input: " + input;

function combineElements(array){
    var lastRange = array[0];
    var output = [];
    for(var index = 1; index < array.length; index++){
        if(lastRange[lastRange.length-1] == array[index][0]){
            lastRange = lastRange.substring(0, lastRange.length-1) + array[index][array[index].length-1];
        }
        else{
            output.push(lastRange);
            lastRange = array[index];
        }
    }
    output.push(lastRange);
    return output;
}

document.getElementById("result").innerHTML = "output: " + combineElements(input);
&#13;
<p id="input"></p>
<p id="result"></p>
&#13;
&#13;
&#13;