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

How To Change What You've Called In A Function To An Array

本文关键字:数组 调用 函数      更新时间:2023-09-26

假设我创建了一个翻转数组元素的函数。例如,该函数接收 [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

我已经寻找了一个小时,但没有成功。有什么帮助吗?

替换

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

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

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

稍后您必须返回连接数组:

return A.join('');

使用的方法:

  • String.prototype.split()

    split() 方法通过将字符串分隔为子字符串,将 String 对象拆分为字符串数组。

  • Array.prototype.join()

    join() 方法将数组的所有元素联接到一个字符串中。

完成工作代码,并进行一些小的更改:

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>');

<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>

使用的函数拆分 :- 这会将字符串拆分为数组。反向 :- 这将用于反转数组。加入 :- 它将加入反向数组JavaScript 字符串数组函数