如何将函数中调用的内容更改为数组

时间:2016-03-12 09:22:57

标签: javascript arrays string function

假设我创建了一个翻转数组元素的函数。例如,函数接受[1,2,3,4]并将其翻转为[4,3,2,1]。我的功能是能够做到这一点。但是,我想做一些似乎不起作用的事情。如果我调用这样的函数:flip("hello"),我希望它将"hello"更改为如下数组:[h,e,l,l,o],将元素翻转为:o,l,l,e,h然后将元素连接在一起以使其成为olleh。这是我迄今为止所做的:

function reverse (A) {
if(typeof(A) == 'string') { A.toString().split(" "); }
var i1 = 0;
var i2 = A.length - 1;

function swap(A, i1, i2) {
var temp = A[i1];
A[i1] = A[i2];
A[i2] = temp;
return A;

}

var index1 = 0;
var index2 = A.length - 1;
var temp = A[index1];

for(let i = index1; i < index2; i++) { 
    swap(A, i, index2); index2--;
}
console.log(A);

}

这根本不起作用。我认为这是因为我没有处理被调用的内容而是处理参数本身。我也尝试过:

if(typeof(reverse(A)) == 'string') {A.toString().split(" "); }

然而,这给了我一个结果:RangeError: Maximum call stack size exceeded

我一直在寻找一个小时但没有成功。有什么帮助吗?

2 个答案:

答案 0 :(得分:1)

替换

A.toString().split(" ");

A = A.split(""); // empty string for splitting, splits every character

因为您需要作业,而A已经是字符串,所以您不需要toString()

稍后您必须使用以下命令返回已连接的数组:

return A.join('');

使用的方法:

完成工作代码并进行一些小改动:

&#13;
&#13;
function reverse(a) {
    function swap(b, i1, i2) {
        var temp = b[i1];
        b[i1] = b[i2];
        b[i2] = temp;
    }

    var index1 = 0,
        index2 = a.length - 1,
        isString = typeof a === 'string';

    if (isString) {
        a = a.split("");
    }

    for (index1 = 0; index1 < index2; index1++) {
        swap(a, index1, index2);
        index2--;
    }

    return isString ? a.join('') : a;
}

document.write('<pre>' + JSON.stringify(reverse([100, 101, 102]), 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(reverse('hello'), 0, 4) + '</pre>');
&#13;
&#13;
&#13;

答案 1 :(得分:0)

<pre><code>
<script>
function myFunction() {
    var str = "hello";
    var splitting = str.split(""); 
    var reversed_array=splitting.reverse();
    var result=reversed_array.join("");
    document.getElementById("demo").innerHTML = result;
    }
</script>
</code></pre>

使用的功能 split: - 将字符串拆分为数组。 反向: - 将用于反转数组。 join: - 它将加入反向数组